Created
December 10, 2018 16:12
-
-
Save thinhbuzz/6e79e112b0e066d9336cd55d843cf17d to your computer and use it in GitHub Desktop.
Download facebook messages by js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(async function (globalOptions) { | |
let batch = 1; | |
window['finalResult'] = { | |
user_id: '', | |
requestToken: '', | |
messages: [], | |
friend: {id: globalOptions.friend_id || 0, name: ''} | |
}; | |
if (!finalResult.friend.id) { | |
finalResult.friend = getFriend(); | |
} | |
if (!finalResult.friend.id) { | |
alert('Không tìm thấy friend id.'); | |
return; | |
} | |
const {requestToken, user_id} = getRequestToken(); | |
if (!requestToken) { | |
alert('Không tìm thấy request token.'); | |
return; | |
} | |
finalResult.user_id = user_id; | |
finalResult.requestToken = requestToken; | |
await fetchMessage({...finalResult, ...globalOptions}); | |
console.info('Done', finalResult); | |
function set(obj, keys, val, safe) { | |
if (safe && typeof val === 'undefined') { | |
return; | |
} | |
if (typeof keys === 'string') { | |
keys = keys.split('.'); | |
} | |
let index = 0; | |
const length = keys.length; | |
let temp = obj; | |
let x; | |
for (; index < length; ++index) { | |
x = temp[keys[index]]; | |
temp = temp[keys[index]] = (index === length - 1 ? val : (x == null ? {} : x)); | |
} | |
} | |
function get(data, key, defValue) { | |
if (typeof data !== 'object') { | |
return defValue; | |
} | |
let result = defValue; | |
key.replace(/([^a-zA-Z_\.]+)/g, '').split('.') | |
.every(function (objKey) { | |
if (data[objKey]) { | |
result = data[objKey]; | |
data = data[objKey]; | |
return true; | |
} | |
result = defValue; | |
return false; | |
}); | |
return typeof result === 'function' ? result() : result; | |
} | |
function pick(obj, keys) { | |
const result = {}; | |
keys.forEach(key => { | |
set(result, key, get(obj, key)); | |
}); | |
return result; | |
} | |
function queryStringify(obj) { | |
const items = []; | |
for (let prop in obj) { | |
if (obj.hasOwnProperty(prop)) { | |
items.push(`${prop}=${encodeURIComponent(obj[prop] + '')}`); | |
} | |
} | |
return items.join('&'); | |
} | |
function request(options) { | |
return new Promise((resolve, reject) => { | |
const xhttp = new XMLHttpRequest(); | |
xhttp.onreadystatechange = function () { | |
if (this.readyState === 4) { | |
try { | |
const rawData = xhttp.responseText.match(/^([^\n]+)\n(.*)$/m)[1]; | |
const data = JSON.parse(rawData); | |
const rawMessages = get(data, 'buzz.data.message_thread.messages.nodes'); | |
if (!Array.isArray(rawMessages)) { | |
return resolve({has_previous_page: false}); | |
} | |
options.before = rawMessages[0].timestamp_precise; | |
rawMessages.reverse(); | |
rawMessages.some(item => { | |
if (options.after && item.timestamp_precise < options.after) { | |
window['buzz_cancel'] = 'stop by after'; | |
return true; | |
} | |
if (options.maxMessages && options.messages.length === options.maxMessages) { | |
window['buzz_cancel'] = 'stop by max message'; | |
return true; | |
} | |
const message = pick(item, ['__typename', 'message.text', 'message_sender.id', 'timestamp_precise']); | |
if (item.__typename !== 'UserMessage') { | |
if (['VoiceCallMessage', 'VideoCallMessage'].indexOf(item.__typename) > -1) { | |
message.snippet = item.snippet; | |
options.messages.push(message); | |
} | |
return; | |
} | |
if (item.sticker) { | |
message.sticker = pick(item.sticker, ['label', 'url', 'width', 'height']); | |
} | |
if (item.extensible_attachment) { | |
message.extensible_attachment = pick(item.extensible_attachment.story_attachment, [ | |
'description.text', | |
'url' | |
]); | |
} | |
if (item.blob_attachments[0]) { | |
message.blob_attachments = item.blob_attachments.map(blob_attachment => { | |
let result; | |
switch (blob_attachment.__typename) { | |
case 'MessageAnimatedImage': | |
result = pick(blob_attachment.animated_image, ['uri', 'height', 'width']); | |
result.__typename = blob_attachment.__typename; | |
result.filename = blob_attachment.filename; | |
break; | |
case 'MessageImage': | |
result = pick(blob_attachment.large_preview, ['uri', 'height', 'width']); | |
result.thumbnail = blob_attachment.thumbnail.uri; | |
result.filename = blob_attachment.filename; | |
result.__typename = blob_attachment.__typename; | |
break; | |
case 'MessageFile': | |
result = pick(blob_attachment, ['filename', 'url']); | |
result.__typename = blob_attachment.__typename; | |
break; | |
case 'MessageVideo': | |
case 'MessageAudio': | |
result = pick(blob_attachment, ['filename', 'playable_url', 'playable_duration_in_ms']); | |
result.__typename = blob_attachment.__typename; | |
break; | |
} | |
return result; | |
}) | |
.filter(item => !!item); | |
} | |
options.messages.push(message); | |
}); | |
return resolve({ | |
has_previous_page: !!get(data, 'buzz.data.message_thread.messages.page_info.has_previous_page', false) | |
}); | |
} catch (error) { | |
return reject(error); | |
} | |
} | |
}; | |
xhttp.open('POST', location.origin + '/api/graphqlbatch/?dpr=1', true); | |
xhttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded, application/x-www-form-urlencoded'); | |
xhttp.setRequestHeader('x-msgr-region', 'SGP'); | |
xhttp.send(queryStringify({ | |
'batch_name': 'MessengerGraphQLThreadFetcher', | |
'__user': options.user_id, | |
'__a': '1', | |
'fb_dtsg': options.requestToken, | |
'queries': JSON.stringify({ | |
'buzz': { | |
'doc_id': '2294242067312755', | |
'query_params': { | |
'id': options.friend.id, | |
'message_limit': options.perPage, | |
'load_messages': true, | |
'load_read_receipts': true, | |
'load_delivery_receipts': true, | |
'before': options.before | |
} | |
} | |
}) | |
})); | |
}); | |
} | |
async function fetchMessage(options) { | |
if (window['buzz_cancel']) { | |
console.warn(window['buzz_cancel']); | |
return; | |
} | |
if (options.before instanceof Date) { | |
options.before = options.before.getTime(); | |
} | |
if (options.after instanceof Date) { | |
options.after = options.after.getTime(); | |
} | |
const result = await request(options); | |
console.info(`Batch ${batch++} completed`); | |
if (result.has_previous_page) { | |
await fetchMessage(options); | |
} | |
} | |
function getFriend() { | |
const currentTab = document.querySelector('[id^=row_header_id_user]>a[tabindex="0"]') | |
|| document.querySelector('[id^=row_header_id_thread]>a[tabindex="0"]'); | |
if (!currentTab) { | |
return 0; | |
} | |
return { | |
id: currentTab.parentNode.id.replace(/(^[^:]+):([0-9]+)$/g, '$2'), | |
name: currentTab.querySelector('[data-tooltip-content]').getAttribute('data-tooltip-content') | |
}; | |
} | |
function getRequestToken() { | |
const result = {requestToken: '', user_id: ''}; | |
Array.prototype.some.call(document.querySelectorAll('script'), script => { | |
if (!script.textContent) { | |
return false; | |
} | |
if (!result.requestToken) { | |
const token = script.textContent.match(/"token":"([^"]+)"/); | |
if (token) { | |
result.requestToken = token[1]; | |
} | |
} | |
if (!result.user_id) { | |
const user_id = script.textContent.match(/"USER_ID":"([^"]+)"/); | |
if (user_id) { | |
result.user_id = user_id[1]; | |
} | |
} | |
return result.requestToken && result.user_id; | |
}); | |
return result; | |
} | |
})({ | |
perPage: 100, | |
maxMessages: Infinity, | |
friend_id: 0 | |
// before: new Date(year, month (0-11), day, hours, minutes, seconds, milliseconds), | |
// after: new Date(year, month (0-11), day, hours, minutes, seconds, milliseconds), | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.facebook.com/messages/t/01234567890
orhttps://www.messenger.com/t/01234567890
finalResult
, it is json result