4chan-x/src/General/lib/databoard.class

93 lines
2.6 KiB
Plaintext
Executable File

class DataBoard
@keys = ['hiddenThreads', 'hiddenPosts', 'lastReadPosts', 'yourPosts', 'watchedThreads']
constructor: (@key, sync, dontClean) ->
@data = Conf[key]
$.sync key, @onSync
@clean() unless dontClean
return unless sync
# Chrome also fires the onChanged callback on the current tab,
# so we only start syncing when we're ready.
init = =>
$.off d, '4chanXInitFinished', init
@sync = sync
$.on d, '4chanXInitFinished', init
save: -> $.set @key, @data
delete: ({boardID, threadID, postID}) ->
$.forceSync @key
if postID
return unless @data.boards[boardID]?[threadID]
delete @data.boards[boardID][threadID][postID]
@deleteIfEmpty {boardID, threadID}
else if threadID
return unless @data.boards[boardID]
delete @data.boards[boardID][threadID]
@deleteIfEmpty {boardID}
else
delete @data.boards[boardID]
@save()
deleteIfEmpty: ({boardID, threadID}) ->
$.forceSync @key
if threadID
unless Object.keys(@data.boards[boardID][threadID]).length
delete @data.boards[boardID][threadID]
@deleteIfEmpty {boardID}
else unless Object.keys(@data.boards[boardID]).length
delete @data.boards[boardID]
set: ({boardID, threadID, postID, val}) ->
$.forceSync @key
if postID isnt undefined
((@data.boards[boardID] or= {})[threadID] or= {})[postID] = val
else if threadID isnt undefined
(@data.boards[boardID] or= {})[threadID] = val
else
@data.boards[boardID] = val
@save()
get: ({boardID, threadID, postID, defaultValue}) ->
$.forceSync @key
if board = @data.boards[boardID]
unless threadID
if postID
for ID, thread in board
if postID of thread
val = thread[postID]
break
else
val = board
else if thread = board[threadID]
val = if postID
thread[postID]
else
thread
val or defaultValue
clean: ->
$.forceSync @key
for boardID, val of @data.boards
@deleteIfEmpty {boardID}
now = Date.now()
if (@data.lastChecked or 0) < now - 2 * $.HOUR
@data.lastChecked = now
for boardID of @data.boards
for threadID of @data.boards[boardID]
@ajaxClean boardID, threadID
@save()
ajaxClean: (boardID, threadID) ->
$.ajax "//a.4cdn.org/#{boardID}/thread/#{threadID}.json",
onloadend: (e) =>
if e.target.status is 404
@delete {boardID, threadID}
,
type: 'head'
onSync: (data) =>
@data = data or boards: {}
@sync?()