无忧启动论坛

 找回密码
 注册
搜索
系统gho:最纯净好用系统下载站投放广告、加入VIP会员,请联系 微信:wuyouceo
查看: 1023|回复: 9
打印 上一主题 下一主题

[求助] 帮我修改.js。使XX显示时间变短,谢谢

[复制链接]
跳转到指定楼层
1#
发表于 2025-5-28 10:16:33 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 yyz2191958 于 2025-5-28 10:52 编辑


gitee.rar (2.92 KB, 下载次数: 3)
==============================
gitee.js:
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoGitTreesSha 获取项目文件和递归所有文件
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取文件内容
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoGitBlobsSha 获取文件Blob
// https://gitee.com/api/v5/swagger ... nerRepoContentsPath 新建文件
// https://gitee.com/api/v5/swagger#/putV5ReposOwnerRepoContentsPath 更新文件
// https://gitee.com/api/v5/swagger ... nerRepoContentsPath 删除文件
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoBranches 获取所有分支
// https://gitee.com/api/v5/swagger#/postV5ReposOwnerRepoBranches 创建分支
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoCommits 仓库的所有提交(分页)
// https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoCommitsSha 仓库的某个提交
// inside: owner repo path content message branch
const git_url = 'https://gitee.com/api'
const header = {'Content-type': 'application/json;charset=UTF-8' }
const git_key = ['access_token','owner','repo','version']
const initext = 'ZGQK'
function Gitee() {
    /**
     * API文档 https://gitee.com/api/v5/swagger ... nerRepoContentsPath 新建文件
     * @param {*} path
     * @param {*} content
     * @param {*} message
     * @param {*} branch
     */
    this.create = function (path,content,message,branch) {
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
            let data = {
                'access_token':  access_token,
                'content': window.btoa(content),
                'message': message,
                'branch': branch,
            }
            fetch(url, {
                method: 'POST',
                body: JSON.stringify(data),
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '创建 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log('创建' + path,resp)
            })
        })
    }

    /**
     * API文档:https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
     * @param {*} path 文件路径
     * @param {*} ref 分支、tag或commit。默认: 仓库的默认分支(通常是master)
     */
    this.getlist = function (path,ref,element,elenum) {
        chrome.storage.local.get(git_key, function (result) {
            console.log('result', result)
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            let version = result.version
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token + '&ref=' + ref
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log('getlist', resp)
                if (resp['message'] != undefined) {
                    console.log('error',resp)
                } else {
                    resp.forEach((vds) => {
                        var op = document.createElement('option');
                        op.setAttribute('label', vds['name']);
                        op.setAttribute('value', vds['name']);
                        op.setAttribute('select', 'select')
                        element.appendChild(op);
                    })
                    elenum.innerText = resp.length
                }
            })
        })
    }

    /**
     * API文档:https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
     * @param {*} path 文件路径
     * @param {*} storage
     */
    this.getTodo = function (path,storage) {
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            let version = result.version
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log(resp)
                let info = JSON.parse(decodeURIComponent(window.atob(resp['content'])))

                try {
                storage.set({
                    easyTodoStorage: info
                })
                } catch (e) {
                // do nothing
                } finally {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'images/icon16.png',
                    title: '更新本地书签',
                    message: '同步完成 '
                })
                }
            })
        })
    }

    // 获取指定文件内容
    /**
     * API文档:https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoGitBlobsSha 获取文件Blob
     * @param {*} sha
     */
    this.get = function (sha) {
        chrome.bookmarks.getTree((re) => {
            chrome.storage.local.set({'repostatus': false}, () => {
                removeall(re)

                chrome.storage.local.get(git_key, function (result) {
                    let access_token = result.access_token
                    let owner = result.owner
                    let repo = result.repo
                    let url = git_url + '/v5/repos/' + owner + '/' + repo + '/commits/' + sha + '?access_token=' + access_token
                    console.log(url)
                    if (owner === '' || owner === undefined) {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('未配置认证信息 true')
                            console.log('reset repostatus === true')
                        })
                        return
                    }
                    fetch(url, {
                        method: 'GET',
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('error true',error)
                            console.log('reset repostatus === true')
                        })
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '获取文件Blob ' + sha,
                            message: error
                        })
                    })
                    .then((resp) => {
                        let url = git_url + '/v5/repos/' + owner + '/' + repo + '/git/blobs/' + resp['files'][0]['sha'] + '?access_token=' + access_token
                        fetch(url, {
                            method: 'GET',
                            headers: header
                        }).then(res => res.json())
                        .catch((error) => {
                            chrome.notifications.create(null, {
                                type: 'basic',
                                iconUrl: 'img/icon.png',
                                title: '获取文件Blob ' + resp['files'][0]['sha'],
                                message: error
                            })
                        })
                        .then((resp2) => {
                            console.log(resp2)
                            if (resp2['message'] == undefined) {
                                let info = JSON.parse(decodeURIComponent(window.atob(resp2['content'])))
                                try {
                                    addAll(info[0].children,'')
                                } catch (e) {
                                    console.log('error',e)
                                } finally {
                                    chrome.notifications.create(null, {
                                        type: 'basic',
                                        iconUrl: 'images/icon16.png',
                                        title: '切换等待10秒',
                                        message: '请勿执行书签操作,否则手工完成同步操作'
                                    })
                                    setTimeout(() => {
                                    chrome.storage.local.set({ 'repostatus': true }, () => {
                                        chrome.notifications.create(null, {
                                        type: 'basic',
                                        iconUrl: 'images/icon16.png',
                                        title: '更新本地书签完成',
                                        message: '启动书签自动同步功能'
                                        })
                                    })
                                    },10000);
                                }
                            } else {
                                console.log('error get ',resp2)
                            }
                        })
                    })
                })
            })
        })
    }

    // 获取指定文件内容
    /**
     * API文档:https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoGitBlobsSha 获取文件Blob
     * @param {*} sha
     */
    this.getrecovery = function (path) {
        chrome.bookmarks.getTree((re) => {
            chrome.storage.local.set({'repostatus': false}, () => {
                removeall(re)

                chrome.storage.local.get(git_key, function (result) {
                    let access_token = result.access_token
                    let owner = result.owner
                    let repo = result.repo
                    let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
                    console.log(url)
                    if (owner === '' || owner === undefined) {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('未配置认证信息 true')
                            console.log('reset repostatus === true')
                        })
                        return
                    }

                    fetch(url, {
                        method: 'GET',
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.storage.local.set({ 'repostatus': true }, () => {
                            alert('error true',error)
                            console.log('reset repostatus === true')
                        })
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '获取文件Blob ' + path,
                            message: error
                        })
                    })
                    .then((resp) => {
                        console.log(resp)
                        let info = JSON.parse(decodeURIComponent(window.atob(resp['content'])))
                        try {
                            addAll(info[0].children,'')
                        } catch (e) {
                            console.log('error',e)
                        } finally {
                            chrome.notifications.create(null, {
                                type: 'basic',
                                iconUrl: 'images/icon16.png',
                                title: '切换等待10秒',
                                message: '请勿执行书签操作,否则手工完成同步操作'
                            })
                            setTimeout(() => {
                            chrome.storage.local.set({ 'repostatus': true }, () => {
                                chrome.notifications.create(null, {
                                type: 'basic',
                                iconUrl: 'images/icon16.png',
                                title: '更新本地书签完成',
                                message: '启动书签自动同步功能'
                                })
                            })
                            },10000);
                        }
                        // return window.atob(resp.content)
                    })
                })
            })
        })
    }

    /**
     * API文档: https://gitee.com/api/v5/swagger#/putV5ReposOwnerRepoContentsPath 更新文件
     * @param {*} sha
     * @param {*} message
     */
    this.updateTagsSha = function (sha,message) {
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo

            chrome.bookmarks.getTree((re) => {
                let data = {
                    "access_token": access_token,
                    "content": window.btoa(encodeURIComponent(JSON.stringify(re))),
                    "sha": sha,
                    "message": message
                }

                let put_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
                fetch(put_url, {
                    method: 'PUT',
                    body: JSON.stringify(data),
                    headers: header
                }).then(res => res.json())
                .catch((error) => {
                    chrome.notifications.create(null, {
                        type: 'basic',
                        iconUrl: 'img/icon.png',
                        title: '上传全量书签错误',
                        message: error
                    })
                })
                .then((resp) => {
                    console.log(resp)
                    chrome.notifications.create(null, {
                        type: 'basic',
                        iconUrl: 'img/icon.png',
                        title: '上传全量书签',
                        message: '成功'
                    })
                })
            })
        })
    }

    /**
     * API文档: https://gitee.com/api/v5/swagger#/putV5ReposOwnerRepoContentsPath 更新文件
     * @param {*} path
     * @param {*} message
     * @param {*} ref
     */
    this.updateTags = function (path,message,ref) {
        let _this = this
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo

            // https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token + '&ref=' + ref
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log('gitee get success' + JSON.stringify(resp), resp['sha'])
                if (resp['sha'] == undefined) {
                    _this.create(path,initext,'init','master')
                    _this.updateTags(path,message,ref)
                    return
                }
                chrome.bookmarks.getTree((re) => {
                    let data = {
                        "access_token": access_token,
                        "content": window.btoa(encodeURIComponent(JSON.stringify(re))),
                        "sha": resp['sha'],
                        "message": message
                    }

                    let put_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
                    fetch(put_url, {
                        method: 'PUT',
                        body: JSON.stringify(data),
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '上传全量书签错误',
                            message: error
                        })
                    })
                    .then((resp) => {
                        console.log(resp)
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '上传全量书签',
                            message: '成功'
                        })
                    })
                })
            })
        })
    }

    /**
     * API文档: todo 远程同步TODOLIST
     * @param {*} path
     * @param {*} message
     * @param {*} ref
     */
    this.updateTodo = function (path,message) {
        let _this = this
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo

            // https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoContents(Path) 获取仓库具体路径下的内容
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                console.log('gitee get success' + JSON.stringify(resp), resp['sha'])
                if (resp['sha'] == undefined) {
                    _this.create(path,initext,'init','master')
                    _this.updateTodo(path,message)
                    return
                }
                chrome.bookmarks.getTree((re) => {
                    let data = {
                        "access_token": access_token,
                        "content": window.btoa(encodeURIComponent(JSON.stringify(re))),
                        "sha": resp['sha'],
                        "message": message
                    }

                    // https://gitee.com/api/v5/swagger#/putV5ReposOwnerRepoContentsPath 更新文件
                    let put_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path
                    fetch(put_url, {
                        method: 'PUT',
                        body: JSON.stringify(data),
                        headers: header
                    }).then(res => res.json())
                    .catch((error) => {
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '上传全量书签错误',
                            message: error
                        })
                    })
                    .then((resp) => {
                        console.log(resp)
                        chrome.notifications.create(null, {
                            type: 'basic',
                            iconUrl: 'img/icon.png',
                            title: '上传全量书签',
                            message: '成功'
                        })
                    })
                })
            })
        })
    }

    /**
     * API文档:https://gitee.com/api/v5/swagger ... nerRepoContentsPath 删除文件
     * @param {*} path
     * @param {*} message
     */
    this.delete = function (path,message) {
        chrome.storage.local.get(git_key, function (result) {
            let _this = this
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo

            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '获取仓库路径 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                let del_url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token + '&sha=' + resp['sha'] + '&message=' + message
                fetch(del_url, {
                    method: 'DELETE',
                    headers: header
                }).then(res => res.json())
                .catch((error) => {
                    console.error('Error:', error)
                })
                .then((resp) => {
                    console.log('github delete success' + JSON.stringify(resp))
                    chrome.notifications.create(null, {
                        type: 'basic',
                        iconUrl: 'img/icon.png',
                        title: '书签删除',
                        message: '远程书签 ' + path + ' 删除完毕!'
                    })
                })
            })
        })
    }

    /**
     * API文档:https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoCommits 仓库的所有提交(分页)
     * @param {*} path 包含该文件的提交
     * @param {*} page 当前的页码
     * @param {*} per_page 每页的数量,最大为 100
     */
    this.getallcommit = function (path,page,per_page,element) {
        chrome.storage.local.get(git_key, function (result) {
            let access_token = result.access_token
            let owner = result.owner
            let repo = result.repo
            let url = git_url + '/v5/repos/' + owner + '/' + repo + '/commits?access_token=' + access_token + '&path=' + path + '&page=' + page + '&per_page=' + per_page
            fetch(url, {
                method: 'GET',
                headers: header
            }).then(res => res.json())
            .catch((error) => {
                chrome.notifications.create(null, {
                    type: 'basic',
                    iconUrl: 'img/icon.png',
                    title: '仓库的所有提交 ' + path,
                    message: error
                })
            })
            .then((resp) => {
                // console.log(resp)
                // return resp
                resp.forEach((vds) => {
                    var op = document.createElement('option');
                    op.setAttribute('label', vds['commit']['message']);
                    op.setAttribute('value', vds['sha']);
                    op.setAttribute('select', 'select')
                    element.appendChild(op);
                })
            })
        })
    }

    /**
     * 本地保存reponame
     * @param {*} name
     */
    this.saveName = function (name) {
        chrome.storage.local.set({'reponame': name}, () => {
            console.log('set repo name ok')
        })
    }
}




2#
 楼主| 发表于 2025-5-28 10:24:54 | 只看该作者
本帖最后由 yyz2191958 于 2025-5-28 10:53 编辑

github.rar (2.68 KB, 下载次数: 1)
github.js:
function Github() {
  this.user = ''
  this.repos = ''
  this.token = ''
  this.key = ['username', 'repos', 'token']

  this.url = 'https://api.github.com'
  this.tags = 'tags'
  this.session = 'session'
  this.bookmarks = 'bookmarks'

  this.stringtobase64 = function (info) {
    return window.btoa(info)
  }

  this.base64tostring = function (info) {
    return window.atob(info)
  }

  /*
   API文档:https://developer.github.com/v3/repos/contents/#create-or-update-a-file
   传输方法:PUT
   访问路径:https://api.github.com/repos/用户名/仓库名/contents/文件路径
   JSON格式:
   {
   "message": "commit from INSOMNIA",
   "content": "$sha="
   }
   */
  this.create = function (filepath) {
    var data = {
      'message': 'commit init',
      'content': 'eyJkZWZhdWx0IjpbeyJuYW1lIjoidGl0bGUiLCJ1cmwiOiJodHRwOi8vYmFpZHUuY29tIiwiaWNvbiI6IjEyMyIsInRpbWUiOiIyMDE5LTAxLTAxIn1dfQo='
    }

    chrome.storage.local.get(this.key, function (result) {
      this.url = 'https://api.github.com'
      this.user = result.username
      this.repos = result.repos
      this.token = result.token
      this.headers = { 'Authorization': 'token ' + this.token, 'Content-type': 'application/json' }
      if (this.user === '' || this.user === undefined) {
        alert('未配置认证信息')
        return
      }

      fetch(this.url + '/repos/' + this.user + '/' + this.repos + '/contents/' + filepath, {
        method: 'PUT',
        body: JSON.stringify(data),
        headers: new Headers({
          'Content-Type': 'application/json',
          'Authorization': 'token ' + this.token
        })
      }).then(res => res.json())
        .catch((error) => {
          chrome.notifications.create(null, {
            type: 'basic',
            iconUrl: 'img/icon.png',
            title: '初始化' + filepath + '目录',
            message: error
          })
        })
        .then((response) => {
          console.log('初始化目录' + filepath + ' 成功')
        })
    })
  }

  // 获取远程列表
  this.getlist = function (filepath, element, elenum) {
    chrome.storage.local.get(this.key, function (result) {
      this.url = 'https://api.github.com'
      this.user = result.username
      this.repos = result.repos
      this.token = result.token
      this.headers = { 'Authorization': 'token ' + this.token, 'Content-type': 'application/json' }
      if (this.user === '' || this.user === undefined) {
        alert('未配置认证信息')
        return
      }

      fetch(this.url + '/repos/' + this.user + '/' + this.repos + '/contents/' + filepath, {
        method: 'GET',
        headers: new Headers({
          'Content-Type': 'application/json',
          'Authorization': 'token ' + this.token
        })
      }).then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then((result) => {
          result.forEach((vds) => {
            var op = document.createElement('option');
            op.setAttribute('label', vds['name']);
            op.setAttribute('value', vds['name']);
            op.setAttribute('select', 'select')
            element.appendChild(op);
          })

          elenum.innerText = result.length
        })
    })
  }

  // 远程加载
  this.get = function (filepath) {
    // 全量清空 然后再加载
    chrome.bookmarks.getTree((re) => {
      removeall(re)

      chrome.storage.local.get(this.key, function (result) {
        this.url = 'https://api.github.com'
        this.user = result.username
        this.repos = result.repos
        this.token = result.token
        this.headers = { 'Authorization': 'token ' + this.token, 'Content-type': 'application/json' }
        if (this.user === '' || this.user === undefined) {
          alert('未配置认证信息')
          return
        }

        fetch(this.url + '/repos/' + this.user + '/' + this.repos + '/contents/' + filepath, {
          method: 'GET',
          headers: new Headers({
            'Content-Type': 'application/json',
            'Authorization': 'token ' + this.token
          })
        }).then(res => res.json())
          .catch(error => console.error('Error:', error))
          .then((result) => {
            let info = JSON.parse(decodeURIComponent(window.atob(result['content'])))

            try {
              addAll(info[0].children, '')
            } catch (e) {
              // do nothing
            } finally {
              chrome.notifications.create(null, {
                type: 'basic',
                iconUrl: 'img/icon.png',
                title: '更新本地书签',
                message: '同步完成 '
              })
            }
          })
      })
    })
  }

  // todo 远程同步
  this.updateTags = function (filepath, message) {
    let _this = this
    chrome.storage.local.get(this.key, function (result) {
      // _this.create(filepath)
      let _this2 = this
      this.url = 'https://api.github.com'
      this.user = result.username
      this.repos = result.repos
      this.token = result.token
      if (this.user === '' || this.user === undefined) {
        alert('user is nil')
        return
      }

      var urls = this.url + '/repos/' + this.user + '/' + this.repos + '/contents/' + filepath

      fetch(urls, {
        method: 'GET',
        headers: new Headers({
          'Content-Type': 'application/json',
          'Authorization': 'token ' + this.token
        })
      }).then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then((result) => {
          console.log('github get success' + JSON.stringify(result), result['sha'])
          // chrome.bookmarks.getChildren('1',(re) => {
          chrome.bookmarks.getTree((re) => {
            if (result['message'] === 'Not Found') {
              console.log('not found create it')
            }
            // 'content': window.btoa(encodeURIComponent(JSON.stringify(re))),
            // 'content': window.btoa(unescape(encodeURIComponent(JSON.stringify(re)))),
            var data = {
              'message': '全量同步bookmarks ' + message,
              'content': window.btoa(encodeURIComponent(JSON.stringify(re))),
              'sha': result['sha']
            }

            fetch(urls, {
              method: 'PUT',
              body: JSON.stringify(data),
              headers: new Headers({
                'Content-Type': 'application/json',
                'Authorization': 'token ' + _this2.token
              })
            }).then(res => res.json())
              .catch((error) => {
                chrome.notifications.create(null, {
                  type: 'basic',
                  iconUrl: 'img/icon.png',
                  title: '上传全量书签错误',
                  message: error
                })
              })
              .then((response) => {
                chrome.notifications.create(null, {
                  type: 'basic',
                  iconUrl: 'img/icon.png',
                  title: '上传全量书签',
                  message: '成功'
                })
              })
          })
        })
    })
  }

  /*
   传输方法:PUT
   访问路径:https://api.github.com/repos/用户名/仓库名/contents/文件路径
   JSON格式:
   {
   "message": "update from INSOMNIA",
   "content": "$sha",
   "sha": "$sha"
   }
   */
  this.update = function (filepath, message, content) {
    chrome.storage.local.get(this.key, function (result) {
      this.url = 'https://api.github.com'
      this.user = result.username
      this.repos = result.repos
      this.token = result.token
      this.headers = { 'Authorization': 'token ' + this.token, 'Content-type': 'application/json' }
      if (this.user === '' || this.user === undefined) {
        alert('user is nil')
        return
      }

      var urls = this.url + '/repos/' + this.user + '/' + this.repos + '/contents/' + filepath
      console.log('urls', urls)

      fetch(urls, {
        method: 'GET',
        headers: new Headers({
          'Content-Type': 'application/json',
          'Authorization': 'token ' + this.token
        })
      }).then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then((result) => {
          console.log('github get success' + JSON.stringify(result), result['sha'])
          var data = {
            'message': message,
            'content': window.btoa(content),
            'sha': result['sha']
          }

          var urls = _this.url + '/repos/' + _this.user + '/' + _this.repos + '/contents/' + filepath
          console.log('urls', urls, data)

          fetch(urls, {
            method: 'PUT',
            body: JSON.stringify(data),
            headers: new Headers({
              'Content-Type': 'application/json',
              'Authorization': 'token ' + this.token
            })
          }).then(res => res.json())
            .catch(error => console.error('Error:', error))
            .then(response => console.log('github update success' + JSON.stringify(response)))
        })
    })
  }

  /*
   传输方法:DELETE
   访问路径:https://api.github.com/repos/用户名/仓库名/contents/文件路径
   JSON格式:
   {
   "message": "delete a file",
   "sha": "$sha"
   }
   */
  this.delete = function (filepath, message) {
    chrome.storage.local.get(this.key, function (result) {
      this.url = 'https://api.github.com'
      this.user = result.username
      this.repos = result.repos
      this.token = result.token
      this.headers = { 'Authorization': 'token ' + this.token, 'Content-type': 'application/json' }
      if (this.user === '' || this.user === undefined) {
        alert('user is nil')
        return
      }

      var urls = this.url + '/repos/' + this.user + '/' + this.repos + '/contents/' + filepath
      console.log('urls', urls)

      fetch(urls, {
        method: 'GET',
        headers: new Headers({
          'Content-Type': 'application/json',
          'Authorization': 'token ' + this.token
        })
      }).then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then((result) => {
          console.log('github get success' + JSON.stringify(result), result['sha'])
          var data = {
            'message': message,
            'branch': 'master',
            'sha': result['sha']
          }

          console.log('urls', urls, data)

          fetch(urls, {
            method: 'DELETE',
            body: JSON.stringify(data),
            headers: new Headers({
              'Content-Type': 'application/json',
              'Authorization': 'token ' + this.token
            })
          }).then(res => res.json())
            .catch(error => console.error('Error:', error))
            .then((response) => {
              console.log('github delete success' + JSON.stringify(response))
              chrome.notifications.create(null, {
                type: 'basic',
                iconUrl: 'img/icon.png',
                title: '书签删除',
                message: '远程书签 ' + filepath + ' 删除完毕!'
              })
            })
        })
    })
  }
}

class Githubs {
  constructor () {
    this.url = 'https://api.github.com'
    this.tags = 'tags'
    this.session = 'session'
    this.bookmarks = 'bookmarks'
    this.key = ['username','repos','token']
    let _this = this
    chrome.storage.local.get(this.key, function (result) {
      _this.user = result.username
      _this.repos = result.repos
      _this.token = result.token
      _this.headers = { 'Authorization': 'token ' + _this.token, 'Content-type': 'application/json' }
      if (_this.user === '' || _this.user === undefined) {
        alert('未配置认证信息')
        return
      }
      console.log(_this.url,this.user,this.token)
    })
  }

  info () {
    console.log(this.user + ' is ' + this.repos)
  }

  puts(filepath,data) {
        return fetch(this.url + '/repos/' + this.user + '/' + this.repos + '/contents/' + filepath, {
      method: 'PUT',
      body: JSON.stringify(data),
      headers: new Headers({
        'Content-Type': 'application/json',
        'Authorization': 'token ' + this.token
      })
    }).then(res => res.json())
    .catch((error) => {
      chrome.notifications.create(null, {
        type: 'basic',
        iconUrl: 'img/icon.png',
        title: '初始化' + filepath + '目录',
        message: error
      })
    })
    .then((response) => {
      console.log('初始化目录' + filepath + ' 成功')
    })
  }

  gets(filepath) {
    return fetch(this.url + '/repos/' + this.user + '/' + this.repos + '/contents/' + filepath, {
      method: 'GET',
      headers: new Headers({
        'Content-Type': 'application/json',
        'Authorization': 'token ' + this.token
      })
    }).then(res => res.json())
    .catch(error => console.error('Error:', error))
    .then((result) => {
      console.log('result',result)
    })
  }

  deletes(filepath,data) {
    return fetch(urls, {
      method: 'DELETE',
      body: JSON.stringify(data),
      headers: new Headers({
        'Content-Type': 'application/json',
        'Authorization': 'token ' + this.token
      })
    }).then(res => res.json())
    .catch(error => console.error('Error:', error))
    .then((response) => {
      console.log('github delete success' + JSON.stringify(response))
      chrome.notifications.create(null, {
        type: 'basic',
        iconUrl: 'img/icon.png',
        title: '书签删除',
        message: '远程书签 ' + filepath + ' 删除完毕!'
      })
    })
  }

  /**
   * 新建文件
   * @param {*} filepath
   */
  create(filepath) {
    var data = {
      'message': 'commit init',
      'content': 'eyJkZWZhdWx0IjpbeyJuYW1lIjoidGl0bGUiLCJ1cmwiOiJodHRwOi8vYmFpZHUuY29tIiwiaWNvbiI6IjEyMyIsInRpbWUiOiIyMDE5LTAxLTAxIn1dfQo='
    }
    return new Promise((resolve,reject) => {
      this.puts(filepath,data).catch(res => {
        reject(res)
      }).catch(res => {
        resolve(res)
      })
    })
  }

  /**
   * 获取远程列表
   * @param {*} filepath
   */
  getlist (filepath) {
    return new Promise((resolve,reject) => {
      this.gets(filepath).catch(res => {
        reject(res)
      }).catch(res => {
        resolve(res)
      })
    })
  }

  // 远程加载
  /**
   *
   * @param {*} filepath
   */
  getremote (filepath) {
    this.getlist(filepath).then(result =>{
      let info = JSON.parse(decodeURIComponent(window.atob(result['content'])))

      try {
        addAll(info[0].children, '')
      } catch (e) {
        // do nothing
      } finally {
        chrome.notifications.create(null, {
          type: 'basic',
          iconUrl: 'img/icon.png',
          title: '更新本地书签',
          message: '同步完成 '
        })
      }
    })
  }

  // todo 远程同步
  /**
   *
   * @param {*} filepath
   * @param {*} message
   */
  updateTags (filepath,message) {
    return new Promise((resolve,reject) =>{
      this.getlist(filepath).then(result => {
        chrome.bookmarks.getTree(re => {
          if (result['message'] === 'Not Found') {
            console.log('not found create it')
          }
          // 'content': window.btoa(encodeURIComponent(JSON.stringify(re))),
          // 'content': window.btoa(unescape(encodeURIComponent(JSON.stringify(re)))),
          var data = {
            'message': '全量同步bookmarks ' + message,
            'content': window.btoa(encodeURIComponent(JSON.stringify(re))),
            'sha': result['sha']
          }
          return this.puts(filepath,data)
        })
      }).catch(res => {
        reject(res)
      }).catch(res => {
        resolve(res)
      })
    })
  }

  /**
   *
   * @param {*} filepath
   * @param {*} message
   * @param {*} content
   */
  update(filepath,message,content) {
    return new Promise((resolve,reject) => {
      this.getlist(filepath).then(result => {
        var data = {
          'message': message,
          'content': window.btoa(content),
          'sha': result['sha']
        }
        return this.puts(filepath,data)
      }).catch(res => {
        reject(res)
      }).catch(res => {
        resolve(res)
      })
    })
  }

  delete(filepath,message) {
    return new Promise((resolve,reject) => {
      this.getlist(filepath).then(result => {
        var data = {
          'message': message,
          'branch': 'master',
          'sha': result['sha']
        }
        return this.deletes(filepath,data)
      }).catch(res => {
        reject(res)
      }).catch(res => {
        resolve(res)
      })
    })
  }
}

var bb = new Githubs()
bb.info()
console.log(bb.session)
bb.create('111.md')

点评

太长...  详情 回复 发表于 2025-5-28 12:44
回复

使用道具 举报

3#
发表于 2025-5-28 11:29:31 | 只看该作者
这种是不是可以问AI?

点评

我不晓得 谢谢  详情 回复 发表于 2025-5-28 11:30
回复

使用道具 举报

4#
 楼主| 发表于 2025-5-28 11:30:30 | 只看该作者
greatpeng 发表于 2025-5-28 11:29
这种是不是可以问AI?

我不晓得 谢谢
回复

使用道具 举报

5#
发表于 2025-5-28 11:34:37 | 只看该作者

把代码扔过去。文字描述一下你的要求。如果有报错,再把报错扔给他。找个连贯性好点的。比如通义、小艺之类的。

点评

谢谢  详情 回复 发表于 2025-5-28 11:41

评分

参与人数 1无忧币 +5 收起 理由
yyz2191958 + 5

查看全部评分

回复

使用道具 举报

6#
 楼主| 发表于 2025-5-28 11:41:04 | 只看该作者
greatpeng 发表于 2025-5-28 11:34
把代码扔过去。文字描述一下你的要求。如果有报错,再把报错扔给他。找个连贯性好点的。比如通义、小艺之 ...

谢谢
回复

使用道具 举报

7#
发表于 2025-5-28 11:59:12 | 只看该作者
来学习下
回复

使用道具 举报

8#
发表于 2025-5-28 12:44:35 | 只看该作者
yyz2191958 发表于 2025-5-28 10:24
github.js:
function Github() {
  this.user = ''

太长...
  1. // 第一个代码片段(已修复重复 setTimeout)
  2. finally {
  3.     chrome.notifications.create('switchingNotification', {
  4.         type: 'basic',
  5.         iconUrl: 'images/icon16.png',
  6.         title: '切换等待5秒',
  7.         message: '请勿执行书签操作,否则手工完成同步操作'
  8.     });
  9.     setTimeout(() => {
  10.         chrome.storage.local.set({ 'repostatus': true }, () => {
  11.             chrome.notifications.create('completedNotification', {
  12.                 type: 'basic',
  13.                 iconUrl: 'images/icon16.png',
  14.                 title: '更新本地书签完成',
  15.                 message: '启动书签自动同步功能'
  16.             });
  17.             chrome.notifications.clear('switchingNotification');
  18.             setTimeout(() => {
  19.                 chrome.notifications.clear('completedNotification'); // 清除完成通知
  20.             }, 5000);
  21.         });
  22.     }, 5000);
  23. }

  24. // 第二个代码片段
  25. finally {
  26.     chrome.notifications.create('switchingNotification', {
  27.         type: 'basic',
  28.         iconUrl: 'images/icon16.png',
  29.         title: '切换等待5秒',
  30.         message: '请勿执行书签操作,否则手工完成同步操作'
  31.     });
  32.     setTimeout(() => {
  33.         chrome.storage.local.set({ 'repostatus': true }, () => {
  34.             chrome.notifications.create('completedNotification', {
  35.                 type: 'basic',
  36.                 iconUrl: 'images/icon16.png',
  37.                 title: '更新本地书签完成',
  38.                 message: '启动书签自动同步功能'
  39.             });
  40.             chrome.notifications.clear('switchingNotification');
  41.             setTimeout(() => {
  42.                 chrome.notifications.clear('completedNotification'); // 清除完成通知
  43.             }, 5000);
  44.         });
  45.     }, 5000);
  46. }

  47. // 第一个“上传全量书签”通知
  48. .then((resp) => {
  49.     console.log(resp);
  50.     chrome.notifications.create('uploadNotification1', {
  51.         type: 'basic',
  52.         iconUrl: 'img/icon.png',
  53.         title: '上传全量书签',
  54.         message: '成功'
  55.     });
  56.     setTimeout(() => {
  57.         chrome.notifications.clear('uploadNotification1');
  58.     }, 5000);
  59. });

  60. // 第二个“上传全量书签”通知
  61. .then((resp) => {
  62.     console.log(resp);
  63.     chrome.notifications.create('uploadNotification2', {
  64.         type: 'basic',
  65.         iconUrl: 'img/icon.png',
  66.         title: '上传全量书签',
  67.         message: '成功'
  68.     });
  69.     setTimeout(() => {
  70.         chrome.notifications.clear('uploadNotification2');
  71.     }, 5000);
  72. });
复制代码

点评

我慢慢琢磨 谢谢  详情 回复 发表于 2025-5-28 17:37

评分

参与人数 1无忧币 +5 收起 理由
yyz2191958 + 5

查看全部评分

回复

使用道具 举报

9#
发表于 2025-5-28 14:09:33 | 只看该作者
这个论坛什么人才都有啊? 连代码问题都可以问
回复

使用道具 举报

10#
 楼主| 发表于 2025-5-28 17:37:26 | 只看该作者

我慢慢琢磨  谢谢
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|捐助支持|无忧启动 ( 闽ICP备05002490号-1 )

闽公网安备 35020302032614号

GMT+8, 2025-7-7 19:04

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表