amatriain/feedbunch

View on GitHub
FeedBunch-app/app/assets/javascripts/ng-services/ng-UserConfigSvc.js.coffee.erb

Summary

Maintainability
Test Coverage
########################################################
# AngularJS service to load user configuration in the scope.
########################################################

angular.module('feedbunch').service 'userConfigSvc',
['$rootScope', 'csrfTokenSvc', 'timerFlagSvc', 'quickReadingSvc', 'openAllEntriesSvc', 'tourSvc', 'keyboardShortcutsSvc',
($rootScope, csrfTokenSvc, timerFlagSvc, quickReadingSvc, openAllEntriesSvc, tourSvc, keyboardShortcutsSvc)->

  # CSRF token
  token = csrfTokenSvc.get_token()

  # Web worker to retrieve user config
  worker = new Worker '<%= asset_path 'workers/load_user_config_worker' %>'
  worker.onmessage = (e) ->
    if e.data.status == 200 || e.data.status == 304
      user_config_loaded e.data.response
    else if e.data.status == 401 || e.data.status == 422
      $window.location.href = '/login'
    else
      timerFlagSvc.start 'error_loading_user_config'
    $rootScope.$digest()

  #--------------------------------------------
  # PRIVATE FUNCTION: Operations after user config has been loaded
  #--------------------------------------------
  user_config_loaded = (response)->
    $rootScope.open_all_entries = response.open_all_entries
    $rootScope.quick_reading = response.quick_reading
    $rootScope.show_main_tour = response.show_main_tour
    $rootScope.show_mobile_tour = response.show_mobile_tour
    $rootScope.show_feed_tour = response.show_feed_tour
    $rootScope.show_entry_tour = response.show_entry_tour
    $rootScope.show_kb_shortcuts_tour = response.show_kb_shortcuts_tour
    $rootScope.kb_shortcuts_enabled = response.kb_shortcuts_enabled
    $rootScope.kb_shortcuts = response.kb_shortcuts

    # Start running Quick Reading mode, if the user has selected it.
    quickReadingSvc.start() if $rootScope.quick_reading

    # Start lazy-loading images, if all entries are open by default
    openAllEntriesSvc.start() if $rootScope.open_all_entries

    # Show application tours if corresponding user config flags are set to true
    tourSvc.start()

    # Initialize responding to keyboard shortcuts (if the user has them enabled in his config)
    keyboardShortcutsSvc.init()

  service =

    #---------------------------------------------
    # Load user configuration data via AJAX into the root scope
    #---------------------------------------------
    load_config: ->
      worker.postMessage {token: token}

  return service
]