Skip to content

Instantly share code, notes, and snippets.

@BrandonLive
Last active August 21, 2018 17:54
Show Gist options
  • Save BrandonLive/72ff091058a3b90d2350c377e73bd87d to your computer and use it in GitHub Desktop.
Save BrandonLive/72ff091058a3b90d2350c377e73bd87d to your computer and use it in GitHub Desktop.
Tweetium suspend handling
/* Copyright (c) 2018 B-side Software
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
// Excerpt of Tweetium suspend handling code as an example
// Note most of this code is from several years ago,
// thus light on modern ES6+ usage and uses WinJS promises and such.
// In my default.js, using WinJS's Application object (optional),
// it wraps the system suspend event and calls it "oncheckpoint"
var app = WinJS.Application;
app.oncheckpoint = function (args) {
try {
var localSettings = Settings.getLocalSettings();
localSettings.insert("LastSuspendTime", Date.now());
// This lets the current page that the window is navigated to do its own handling
// Tweetium really only has one "page" though...
if (AppInstance.currentPage && AppInstance.currentPage.onSuspend) {
AppInstance.currentPage.onSuspend();
}
var tweetMarkerPromise = Settings.isTweetMarkerEnabled() ?
TweetMarker.uploadLastReadMarkersForInvalidatedScopes() : WinJS.Promise.as(null);
var stopMonitoringPromise = TweetRT.SyncEngine.StopMonitoring();
// I found that Phone is less forgiving about the time you can take to suspend,
// so use a more aggressive timeout there
var timeout = Globals.isPhoneHost ? 1500 : 3000;
var suspendPromises = WinJS.Promise.join([tweetMarkerPromise, stopMonitoringPromise]);
var promise = WinJS.Promise.timeout(timeout).then(function ()
{
localSettings.insert("LastSuccessfulSuspendTime", Date.now());
},
function (error) {
debugger;
// We really don't want to return an error here, even canceled!
});
window.CollectGarbage();
args.setPromise(promise);
}
catch (ex) {
debugger;
}
};
// In the main page class
class MainPage
{
onSuspend() {
if (this.resumeTimeout) {
clearTimeout(this.resumeTimeout);
this.resumeTimeout = null;
}
this.lastHiddenTime = Date.now();
var localSettings = Settings.getLocalSettings();
var scopeDetails = {
accountId: TwitterAPI.getCurrentUserId(),
scopeName: this.currentScope,
};
if (!this.loading) {
this._saveViewState();
}
localSettings.insert("LastScope", JSON.stringify(scopeDetails));
localSettings.insert("LastViewState", JSON.stringify(nav.state));
this.pivotScroller.style.visibility = "hidden";
if (Globals.isPhoneHost) {
// Need to kill inertia or weirdness can happen on phone.
this.pivotScroller.style.overflow = "hidden";
this.scrollViewer.style.overflow = "hidden";
}
if (this.loading) {
this.wasLoadingLastSuspend = true;
}
// If we're still navigating to the current view, cancel that
if (this.loadPromise) {
this.loadPromise.cancel();
}
// If we were loading more tweets because the user scrolled
// close to the bottom, cancel that
if (this.loadMorePromise) {
this.loadMorePromise.cancel();
this.loadMorePromise = null;
}
// Kill timer used to batch tweets sent from the worker thread
if (this._pendingTweetsInterval) {
clearInterval(this._pendingTweetsInterval);
this._pendingTweetsInterval = null;
}
// Free up some memory by dropping UI elements and cached tweets other than
// those for the current view and near the current scroll position
this._compactLists();
this.loading = false;
}
onVisibilityChange () {
Debug.log("HomePage onVisibilityChange: " + (document.hidden ? "hidden" : "visible"));
if (document.hidden) {
this.lastHiddenTime = Date.now();
}
else if (!this.firstLoad) {
this.pivotScroller.style.visibility = "";
this.lastVisibleNotificationTime = Date.now();
this.timelineControl.updateAgeIndicators();
// Make extra sure we know the correct connectivity state.
if (!Utils.isInternetConnectivityAvailable()) {
if (this.networkAvailable) {
this.onNetworkStatusChanged();
}
}
else {
this.networkAvailable = true;
}
}
}
}
// Over in worker thread
const cachedScopeDataMaxAge = 5 * 60 * 1000; // 5 minutes
class TweetMonitor {
stopMonitoring() {
Debug.log("stopMonitoring called");
this._isMonitoring = false;
// Cancel requests for all scopes (e.g. Timeline, Connect, lists, etc)
var promisesToCancel = [];
var dataByScope = this._dataByScope;
Object.keys(dataByScope).forEach(function (scopeName) {
var scopeData = dataByScope[scopeName];
if (scopeData.pendingRequestPromise) {
promisesToCancel.push(scopeData.pendingRequestPromise);
scopeData.pendingRequestPromise = null;
}
});
// Clears per-scope state
this._initScopeData();
var promise = WinJS.Promise.as(null);
if (this._currentStreamPromise) {
Debug.log("stopMonitoring canceling stream promise");
var streamPromise = this._currentStreamPromise;
this._currentStreamPromise = null;
var cancelPromise = streamPromise.then(function () { return null; },
function (error) { return null; });
var timeoutPromise = WinJS.Promise.timeout(600).then(function () { return null; },
function (error) { return null; }); // Give <1 second to cancel, don't return errors. Using _currentStreamPromise here is unreliable.
promise = WinJS.Promise.any([cancelPromise, timeoutPromise]);
streamPromise.cancel();
}
promisesToCancel.forEach(function (promiseToCancel) {
promiseToCancel.cancel();
});
return promise;
}
compactLists(options) {
if (!options) { debugger; }
for (var scopeName in this._dataByScope) {
var scopeData = this._dataByScope[scopeName];
if (!scopeData.noCompaction) {
var isCurrentScope = (scopeName == options.currentScope);
// Revisit this...
// Don't clear recently sync'd data to help the back button to be able to restore position quickly and easily.
var scopeCacheExpired = (scopeData.lastRequestTime && ((Date.now() - scopeData.lastRequestTime) > cachedScopeDataMaxAge));
var isOtherScopeAndExpired = !isCurrentScope && scopeCacheExpired && !scopeData.builtin;
if (isCurrentScope) {
var countToKeep = 50;
if (options.preserveToTweetId) {
for (var i = 0; i < scopeData.tweets.length; i++) {
if (scopeData.tweets[i].id == options.preserveToTweetId) {
countToKeep = i;
break;
}
}
}
if (scopeData.tweets.length > countToKeep) {
var removed = scopeData.tweets.slice(countToKeep);
if (removed.length > 0) {
scopeData.endReached = false;
removed.forEach(function (removedTweet) {
delete scopeData.tweetIds[removedTweet.id];
});
}
scopeData.tweets = scopeData.tweets.slice(0, countToKeep);
}
}
else if (isOtherScopeAndExpired) {
// Non-builtin scopes get purged (unless we're looking at it)
this._resetScopeData(scopeData);
}
}
}
self.CollectGarbage();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment