/src/models/thumbnailjobcollection.js
JavaScript | 106 lines | 56 code | 11 blank | 39 comment | 6 complexity | 83d033b2cfb6db49718bf2d4cf91d538 MD5 | raw file
- define([
- 'config!',
- 'underscore',
- 'backbone',
- 'models/livecollection',
- 'lib/template',
- 'lib/translatekeys'
- ], function (config, util, Backbone, LiveCollection, template, translateKeys) {
-
- // Cache underscore templates for URL endpoints.
- var makeStatusUrl = template(config.thumbnailerStatus),
- makeThumbnailUrl = template(config.thumbnailUrl);
-
- var ThumbnailModel = Backbone.Model.extend({
- // Builds you a thumbnail URL
- src: function () {
- return makeThumbnailUrl({
- thumbnail_key: this.get('id')
- });
- }
- });
-
- var ThumbnailJobCollection = LiveCollection.extend({
- model: ThumbnailModel,
-
- initialize: function (attributes, options) {
- this.jobID = '';
- // Create a URL from jobID, if none set.
- if (options && options.jobID && !this.url) {
- this.jobID = options.jobID;
- this.url = makeStatusUrl({ jobId: this.jobID });
- }
- console.log('New Thumbnail Job Collection ' + this.jobID);
- },
-
- pollUntilFinishedProcessing: function () {
- this.stream({
- interval: 5000,
- tries: 5,
-
- success: function (collection, resp) {
- console.log('Polled Thumbnail Job API (' +
- collection.length + 'ct) ' +
- collection.jobID);
-
- // If it's an XHR success, but not an API success do nothing.
- // TODO: handle API errors.
- if (!collection.isSuccess) return;
- // Get all of the statuses from thumbnails
- var statuses = collection.pluck('status');
- // If all thumbnails are processed, stop polling.
- if (util.indexOf(statuses, 'processing') === -1)
- collection.unstream();
- }
- });
- },
-
- // Defining a custom parse implementation that massages data
- // from our JSON API into a Backbone.Model-compatible format.
- //
- // Sample return data:
- //
- // {
- // "job": "...",
- // "sites": [
- // {
- // "key": "...",
- // "status": "processing",
- // "url": "http://instapaper.com/"
- // }
- // ...
- // ],
- // "success": true
- // }
- //
- // ...which is turned into:
- //
- // [
- // {
- // "id": "...",
- // "status": "processing",
- // "url": "http://instapaper.com/"
- // }
- // ...
- // ]
- parse: function (resp) {
- var results = resp.sites,
- translator = util.bind(translateKeys, this, {
- // Convert key to id, so we can use all of the nice
- // collection/model getters.
- key: 'id',
- status: 'status',
- url: 'url'
- });
- // Make sure JobID is correct
- this.jobID = resp.job;
- // Set if this is an API success
- this.isSuccess = resp.success;
- return (resp && resp.success ? util.map(results, translator) : []);
- }
- });
- return ThumbnailJobCollection;
- });