BookModel.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. package models
  2. import (
  3. "crypto/md5"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/astaxie/beego"
  15. "github.com/astaxie/beego/logs"
  16. "github.com/astaxie/beego/orm"
  17. "github.com/lifei6671/mindoc/conf"
  18. "github.com/lifei6671/mindoc/utils/cryptil"
  19. "github.com/lifei6671/mindoc/utils/filetil"
  20. "github.com/lifei6671/mindoc/utils/requests"
  21. "github.com/lifei6671/mindoc/utils/ziptil"
  22. "gopkg.in/russross/blackfriday.v2"
  23. "encoding/json"
  24. )
  25. // Book struct .
  26. type Book struct {
  27. BookId int `orm:"pk;auto;unique;column(book_id)" json:"book_id"`
  28. // BookName 项目名称.
  29. BookName string `orm:"column(book_name);size(500)" json:"book_name"`
  30. // Identify 项目唯一标识.
  31. Identify string `orm:"column(identify);size(100);unique" json:"identify"`
  32. //是否是自动发布 0 否/1 是
  33. AutoRelease int `orm:"column(auto_release);type(int);default(0)" json:"auto_release"`
  34. //是否开启下载功能 0 是/1 否
  35. IsDownload int `orm:"column(is_download);type(int);default(0)" json:"is_download"`
  36. OrderIndex int `orm:"column(order_index);type(int);default(0)" json:"order_index"`
  37. // Description 项目描述.
  38. Description string `orm:"column(description);size(2000)" json:"description"`
  39. //发行公司
  40. Publisher string `orm:"column(publisher);size(500)" json:"publisher"`
  41. Label string `orm:"column(label);size(500)" json:"label"`
  42. // PrivatelyOwned 项目私有: 0 公开/ 1 私有
  43. PrivatelyOwned int `orm:"column(privately_owned);type(int);default(0)" json:"privately_owned"`
  44. // 当项目是私有时的访问Token.
  45. PrivateToken string `orm:"column(private_token);size(500);null" json:"private_token"`
  46. //状态:0 正常/1 已删除
  47. Status int `orm:"column(status);type(int);default(0)" json:"status"`
  48. //默认的编辑器.
  49. Editor string `orm:"column(editor);size(50)" json:"editor"`
  50. // DocCount 包含文档数量.
  51. DocCount int `orm:"column(doc_count);type(int)" json:"doc_count"`
  52. // CommentStatus 评论设置的状态:open 为允许所有人评论,closed 为不允许评论, group_only 仅允许参与者评论 ,registered_only 仅允许注册者评论.
  53. CommentStatus string `orm:"column(comment_status);size(20);default(open)" json:"comment_status"`
  54. CommentCount int `orm:"column(comment_count);type(int)" json:"comment_count"`
  55. //封面地址
  56. Cover string `orm:"column(cover);size(1000)" json:"cover"`
  57. //主题风格
  58. Theme string `orm:"column(theme);size(255);default(default)" json:"theme"`
  59. // CreateTime 创建时间 .
  60. CreateTime time.Time `orm:"type(datetime);column(create_time);auto_now_add" json:"create_time"`
  61. //每个文档保存的历史记录数量,0 为不限制
  62. HistoryCount int `orm:"column(history_count);type(int);default(0)" json:"history_count"`
  63. //是否启用分享,0启用/1不启用
  64. IsEnableShare int `orm:"column(is_enable_share);type(int);default(0)" json:"is_enable_share"`
  65. MemberId int `orm:"column(member_id);size(100)" json:"member_id"`
  66. ModifyTime time.Time `orm:"type(datetime);column(modify_time);null;auto_now" json:"modify_time"`
  67. Version int64 `orm:"type(bigint);column(version)" json:"version"`
  68. //是否使用第一篇文章项目为默认首页,0 否/1 是
  69. IsUseFirstDocument int `orm:"column(is_use_first_document);type(int);default(0)" json:"is_use_first_document"`
  70. }
  71. func (book *Book) String() string {
  72. ret, err := json.Marshal(*book)
  73. if err != nil {
  74. return ""
  75. }
  76. return string(ret)
  77. }
  78. // TableName 获取对应数据库表名.
  79. func (book *Book) TableName() string {
  80. return "books"
  81. }
  82. // TableEngine 获取数据使用的引擎.
  83. func (book *Book) TableEngine() string {
  84. return "INNODB"
  85. }
  86. func (book *Book) TableNameWithPrefix() string {
  87. return conf.GetDatabasePrefix() + book.TableName()
  88. }
  89. func NewBook() *Book {
  90. return &Book{}
  91. }
  92. //添加一个项目
  93. func (book *Book) Insert() error {
  94. o := orm.NewOrm()
  95. // o.Begin()
  96. _, err := o.Insert(book)
  97. if err == nil {
  98. if book.Label != "" {
  99. NewLabel().InsertOrUpdateMulti(book.Label)
  100. }
  101. relationship := NewRelationship()
  102. relationship.BookId = book.BookId
  103. relationship.RoleId = 0
  104. relationship.MemberId = book.MemberId
  105. err = relationship.Insert()
  106. if err != nil {
  107. logs.Error("插入项目与用户关联 => ", err)
  108. //o.Rollback()
  109. return err
  110. }
  111. document := NewDocument()
  112. document.BookId = book.BookId
  113. document.DocumentName = "空白文档"
  114. document.MemberId = book.MemberId
  115. err = document.InsertOrUpdate()
  116. if err != nil {
  117. //o.Rollback()
  118. return err
  119. }
  120. //o.Commit()
  121. return nil
  122. }
  123. //o.Rollback()
  124. return err
  125. }
  126. func (book *Book) Find(id int,cols ...string) (*Book, error) {
  127. if id <= 0 {
  128. return book, ErrInvalidParameter
  129. }
  130. o := orm.NewOrm()
  131. err := o.QueryTable(book.TableNameWithPrefix()).Filter("book_id", id).One(book,cols...)
  132. return book, err
  133. }
  134. //更新一个项目
  135. func (book *Book) Update(cols ...string) error {
  136. o := orm.NewOrm()
  137. temp := NewBook()
  138. temp.BookId = book.BookId
  139. if err := o.Read(temp); err != nil {
  140. return err
  141. }
  142. if book.Label != "" || temp.Label != "" {
  143. go NewLabel().InsertOrUpdateMulti(book.Label + "," + temp.Label)
  144. }
  145. _, err := o.Update(book, cols...)
  146. return err
  147. }
  148. //复制项目
  149. func (book *Book) Copy(identify string) error {
  150. o := orm.NewOrm()
  151. err := o.QueryTable(book.TableNameWithPrefix()).Filter("identify",identify).One(book)
  152. if err != nil {
  153. beego.Error("查询项目时出错 -> ",err)
  154. return err
  155. }
  156. if err := o.Begin();err != nil {
  157. beego.Error("开启事物时出错 -> ",err)
  158. return err
  159. }
  160. bookId := book.BookId
  161. book.BookId = 0
  162. book.Identify = book.Identify + fmt.Sprintf("%s-%s",identify,strconv.FormatInt(time.Now().UnixNano(), 32))
  163. book.BookName = book.BookName + "[副本]"
  164. book.CreateTime = time.Now()
  165. book.CommentCount = 0
  166. book.HistoryCount = 0
  167. if _,err := o.Insert(book);err != nil {
  168. beego.Error("复制项目时出错 -> ",err)
  169. o.Rollback()
  170. return err
  171. }
  172. var rels []*Relationship
  173. if _,err := o.QueryTable(NewRelationship().TableNameWithPrefix()).Filter("book_id",bookId).All(&rels); err != nil {
  174. beego.Error("复制项目关系时出错 -> ",err)
  175. o.Rollback()
  176. return err
  177. }
  178. for _,rel := range rels {
  179. rel.BookId = book.BookId
  180. rel.RelationshipId = 0
  181. if _,err := o.Insert(rel);err != nil {
  182. beego.Error("复制项目关系时出错 -> ",err)
  183. o.Rollback()
  184. return err
  185. }
  186. }
  187. var docs []*Document
  188. if _,err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id",bookId).Filter("parent_id",0).All(&docs);err != nil && err != orm.ErrNoRows {
  189. beego.Error("读取项目文档时出错 -> ",err)
  190. o.Rollback()
  191. return err
  192. }
  193. if len(docs) > 0 {
  194. if err := recursiveInsertDocument(docs,o, book.BookId,0);err != nil {
  195. beego.Error("复制项目时出错 -> ",err)
  196. o.Rollback()
  197. return err
  198. }
  199. }
  200. return o.Commit()
  201. }
  202. //递归的复制文档
  203. func recursiveInsertDocument(docs []*Document,o orm.Ormer,bookId int,parentId int) error {
  204. for _,doc := range docs {
  205. docId := doc.DocumentId
  206. doc.DocumentId = 0
  207. doc.ParentId = parentId
  208. doc.BookId = bookId
  209. doc.Version = time.Now().Unix()
  210. if _,err := o.Insert(doc);err != nil {
  211. beego.Error("插入项目时出错 -> ",err)
  212. return err
  213. }
  214. var attachList []*Attachment
  215. //读取所有附件列表
  216. if _,err := o.QueryTable(NewAttachment().TableNameWithPrefix()).Filter("document_id",docId).All(&attachList); err == nil {
  217. for _,attach := range attachList {
  218. attach.BookId = bookId
  219. attach.DocumentId = doc.DocumentId
  220. attach.AttachmentId = 0
  221. if _,err := o.Insert(attach);err != nil {
  222. return err
  223. }
  224. }
  225. }
  226. var subDocs []*Document
  227. if _,err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("parent_id",docId).All(&subDocs);err != nil && err != orm.ErrNoRows {
  228. beego.Error("读取文档时出错 -> ",err)
  229. return err
  230. }
  231. if len(subDocs) > 0{
  232. if err := recursiveInsertDocument(subDocs,o,bookId,doc.DocumentId);err != nil {
  233. return err
  234. }
  235. }
  236. }
  237. return nil
  238. }
  239. //根据指定字段查询结果集.
  240. func (book *Book) FindByField(field string, value interface{},cols ...string) ([]*Book, error) {
  241. o := orm.NewOrm()
  242. var books []*Book
  243. _, err := o.QueryTable(book.TableNameWithPrefix()).Filter(field, value).All(&books,cols...)
  244. return books, err
  245. }
  246. //根据指定字段查询一个结果.
  247. func (book *Book) FindByFieldFirst(field string, value interface{}) (*Book, error) {
  248. o := orm.NewOrm()
  249. err := o.QueryTable(book.TableNameWithPrefix()).Filter(field, value).One(book)
  250. return book, err
  251. }
  252. //根据项目标识查询项目
  253. func (book *Book) FindByIdentify(identify string,cols ...string) (*Book, error) {
  254. o := orm.NewOrm()
  255. err := o.QueryTable(book.TableNameWithPrefix()).Filter("identify", identify).One(book,cols...)
  256. return book, err
  257. }
  258. //分页查询指定用户的项目
  259. func (book *Book) FindToPager(pageIndex, pageSize, memberId int) (books []*BookResult, totalCount int, err error) {
  260. relationship := NewRelationship()
  261. o := orm.NewOrm()
  262. sql1 := "SELECT COUNT(book.book_id) AS total_count FROM " + book.TableNameWithPrefix() + " AS book LEFT JOIN " +
  263. relationship.TableNameWithPrefix() + " AS rel ON book.book_id=rel.book_id AND rel.member_id = ? WHERE rel.relationship_id > 0 "
  264. err = o.Raw(sql1, memberId).QueryRow(&totalCount)
  265. if err != nil {
  266. return
  267. }
  268. offset := (pageIndex - 1) * pageSize
  269. sql2 := "SELECT book.*,rel.member_id,rel.role_id,m.account as create_name FROM " + book.TableNameWithPrefix() + " AS book" +
  270. " LEFT JOIN " + relationship.TableNameWithPrefix() + " AS rel ON book.book_id=rel.book_id AND rel.member_id = ?" +
  271. " LEFT JOIN " + relationship.TableNameWithPrefix() + " AS rel1 ON book.book_id=rel1.book_id AND rel1.role_id=0" +
  272. " LEFT JOIN " + NewMember().TableNameWithPrefix() + " AS m ON rel1.member_id=m.member_id " +
  273. " WHERE rel.relationship_id > 0 ORDER BY book.order_index DESC,book.book_id DESC LIMIT " + fmt.Sprintf("%d,%d", offset, pageSize)
  274. _, err = o.Raw(sql2, memberId).QueryRows(&books)
  275. if err != nil {
  276. logs.Error("分页查询项目列表 => ", err)
  277. return
  278. }
  279. sql := "SELECT m.account,doc.modify_time FROM md_documents AS doc LEFT JOIN md_members AS m ON doc.modify_at=m.member_id WHERE book_id = ? LIMIT 1 ORDER BY doc.modify_time DESC"
  280. if err == nil && len(books) > 0 {
  281. for index, book := range books {
  282. var text struct {
  283. Account string
  284. ModifyTime time.Time
  285. }
  286. err1 := o.Raw(sql, book.BookId).QueryRow(&text)
  287. if err1 == nil {
  288. books[index].LastModifyText = text.Account + " 于 " + text.ModifyTime.Format("2006-01-02 15:04:05")
  289. }
  290. if book.RoleId == 0 {
  291. book.RoleName = "创始人"
  292. } else if book.RoleId == 1 {
  293. book.RoleName = "管理员"
  294. } else if book.RoleId == 2 {
  295. book.RoleName = "编辑者"
  296. } else if book.RoleId == 3 {
  297. book.RoleName = "观察者"
  298. }
  299. }
  300. }
  301. return
  302. }
  303. // 彻底删除项目.
  304. func (book *Book) ThoroughDeleteBook(id int) error {
  305. if id <= 0 {
  306. return ErrInvalidParameter
  307. }
  308. o := orm.NewOrm()
  309. book, err := book.Find(id)
  310. if err != nil {
  311. return err
  312. }
  313. o.Begin()
  314. //删除附件,这里没有删除实际物理文件
  315. _,err = o.Raw("DELETE FROM " + NewAttachment().TableNameWithPrefix() + " WHERE book_id=?").Exec()
  316. if err != nil {
  317. o.Rollback()
  318. return err
  319. }
  320. //删除文档
  321. _, err = o.Raw( "DELETE FROM " + NewDocument().TableNameWithPrefix() + " WHERE book_id = ?", book.BookId).Exec()
  322. if err != nil {
  323. o.Rollback()
  324. return err
  325. }
  326. //删除项目
  327. _, err = o.Raw("DELETE FROM " + book.TableNameWithPrefix() + " WHERE book_id = ?", book.BookId).Exec()
  328. if err != nil {
  329. o.Rollback()
  330. return err
  331. }
  332. //删除关系
  333. _, err = o.Raw("DELETE FROM " + NewRelationship().TableNameWithPrefix() + " WHERE book_id = ?", book.BookId).Exec()
  334. if err != nil {
  335. o.Rollback()
  336. return err
  337. }
  338. //删除模板
  339. _,err = o.Raw("DELETE FROM " + NewTemplate().TableNameWithPrefix() + " WHERE book_id = ?",book.BookId).Exec()
  340. if err != nil {
  341. o.Rollback()
  342. return err
  343. }
  344. if book.Label != "" {
  345. NewLabel().InsertOrUpdateMulti(book.Label)
  346. }
  347. os.RemoveAll(filepath.Join(conf.WorkingDirectory, "uploads", "books", strconv.Itoa(id)))
  348. return o.Commit()
  349. }
  350. //分页查找系统首页数据.
  351. func (book *Book) FindForHomeToPager(pageIndex, pageSize, member_id int) (books []*BookResult, totalCount int, err error) {
  352. o := orm.NewOrm()
  353. offset := (pageIndex - 1) * pageSize
  354. //如果是登录用户
  355. if member_id > 0 {
  356. sql1 := "SELECT COUNT(*) FROM md_books AS book LEFT JOIN md_relationship AS rel ON rel.book_id = book.book_id AND rel.member_id = ? WHERE relationship_id > 0 OR book.privately_owned = 0"
  357. err = o.Raw(sql1, member_id).QueryRow(&totalCount)
  358. if err != nil {
  359. return
  360. }
  361. sql2 := `SELECT book.*,rel1.*,member.account AS create_name,member.real_name FROM md_books AS book
  362. LEFT JOIN md_relationship AS rel ON rel.book_id = book.book_id AND rel.member_id = ?
  363. LEFT JOIN md_relationship AS rel1 ON rel1.book_id = book.book_id AND rel1.role_id = 0
  364. LEFT JOIN md_members AS member ON rel1.member_id = member.member_id
  365. WHERE rel.relationship_id > 0 OR book.privately_owned = 0 ORDER BY order_index DESC ,book.book_id DESC LIMIT ?,?`
  366. _, err = o.Raw(sql2, member_id, offset, pageSize).QueryRows(&books)
  367. } else {
  368. count, err1 := o.QueryTable(book.TableNameWithPrefix()).Filter("privately_owned", 0).Count()
  369. if err1 != nil {
  370. err = err1
  371. return
  372. }
  373. totalCount = int(count)
  374. sql := `SELECT book.*,rel.*,member.account AS create_name,member.real_name FROM md_books AS book
  375. LEFT JOIN md_relationship AS rel ON rel.book_id = book.book_id AND rel.role_id = 0
  376. LEFT JOIN md_members AS member ON rel.member_id = member.member_id
  377. WHERE book.privately_owned = 0 ORDER BY order_index DESC ,book.book_id DESC LIMIT ?,?`
  378. _, err = o.Raw(sql, offset, pageSize).QueryRows(&books)
  379. }
  380. return
  381. }
  382. //分页全局搜索.
  383. func (book *Book) FindForLabelToPager(keyword string, pageIndex, pageSize, memberId int) (books []*BookResult, totalCount int, err error) {
  384. o := orm.NewOrm()
  385. keyword = "%" + keyword + "%"
  386. offset := (pageIndex - 1) * pageSize
  387. //如果是登录用户
  388. if memberId > 0 {
  389. sql1 := "SELECT COUNT(*) FROM md_books AS book LEFT JOIN md_relationship AS rel ON rel.book_id = book.book_id AND rel.member_id = ? WHERE (relationship_id > 0 OR book.privately_owned = 0) AND book.label LIKE ?"
  390. err = o.Raw(sql1, memberId, keyword).QueryRow(&totalCount)
  391. if err != nil {
  392. return
  393. }
  394. sql2 := `SELECT book.*,rel1.*,member.account AS create_name FROM md_books AS book
  395. LEFT JOIN md_relationship AS rel ON rel.book_id = book.book_id AND rel.member_id = ?
  396. LEFT JOIN md_relationship AS rel1 ON rel1.book_id = book.book_id AND rel1.role_id = 0
  397. LEFT JOIN md_members AS member ON rel1.member_id = member.member_id
  398. WHERE (rel.relationship_id > 0 OR book.privately_owned = 0) AND book.label LIKE ? ORDER BY order_index DESC ,book.book_id DESC LIMIT ?,?`
  399. _, err = o.Raw(sql2, memberId, keyword, offset, pageSize).QueryRows(&books)
  400. return
  401. } else {
  402. count, err1 := o.QueryTable(NewBook().TableNameWithPrefix()).Filter("privately_owned", 0).Filter("label__icontains", keyword).Count()
  403. if err1 != nil {
  404. err = err1
  405. return
  406. }
  407. totalCount = int(count)
  408. sql := `SELECT book.*,rel.*,member.account AS create_name FROM md_books AS book
  409. LEFT JOIN md_relationship AS rel ON rel.book_id = book.book_id AND rel.role_id = 0
  410. LEFT JOIN md_members AS member ON rel.member_id = member.member_id
  411. WHERE book.privately_owned = 0 AND book.label LIKE ? ORDER BY order_index DESC ,book.book_id DESC LIMIT ?,?`
  412. _, err = o.Raw(sql, keyword, offset, pageSize).QueryRows(&books)
  413. return
  414. }
  415. }
  416. //发布文档
  417. func (book *Book) ReleaseContent(bookId int) {
  418. o := orm.NewOrm()
  419. var docs []*Document
  420. _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).All(&docs, "document_id", "identify", "content")
  421. if err != nil {
  422. beego.Error("发布失败 =>",bookId, err)
  423. return
  424. }
  425. for _, item := range docs {
  426. item.BookId = bookId
  427. item.ReleaseContent()
  428. }
  429. }
  430. //重置文档数量
  431. func (book *Book) ResetDocumentNumber(bookId int) {
  432. o := orm.NewOrm()
  433. totalCount, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).Count()
  434. if err == nil {
  435. _,err = o.Raw("UPDATE md_books SET doc_count = ? WHERE book_id = ?", int(totalCount), bookId).Exec()
  436. if err != nil {
  437. beego.Error("重置文档数量失败 =>",bookId,err)
  438. }
  439. } else {
  440. beego.Error("获取文档数量失败 =>",bookId,err)
  441. }
  442. }
  443. //导入项目
  444. func (book *Book) ImportBook(zipPath string) error {
  445. if !filetil.FileExists(zipPath) {
  446. return errors.New("文件不存在 => " + zipPath)
  447. }
  448. w := md5.New()
  449. io.WriteString(w, zipPath) //将str写入到w中
  450. io.WriteString(w, time.Now().String())
  451. io.WriteString(w, book.BookName)
  452. md5str := fmt.Sprintf("%x", w.Sum(nil)) //w.Sum(nil)将w的hash转成[]byte格式
  453. tempPath := filepath.Join(os.TempDir(), md5str)
  454. if err := os.MkdirAll(tempPath, 0766); err != nil {
  455. beego.Error("创建导入目录出错 => ",err)
  456. }
  457. //如果加压缩失败
  458. if err := ziptil.Unzip(zipPath, tempPath); err != nil {
  459. return err
  460. }
  461. //当导入结束后,删除临时文件
  462. //defer os.RemoveAll(tempPath)
  463. for {
  464. //如果当前目录下只有一个目录,则重置根目录
  465. if entries, err := ioutil.ReadDir(tempPath); err == nil && len(entries) == 1 {
  466. dir := entries[0]
  467. if dir.IsDir() && dir.Name() != "." && dir.Name() != ".." {
  468. tempPath = filepath.Join(tempPath, dir.Name())
  469. break
  470. }
  471. } else {
  472. break
  473. }
  474. }
  475. tempPath = strings.Replace(tempPath, "\\", "/", -1)
  476. docMap := make(map[string]int, 0)
  477. o := orm.NewOrm()
  478. o.Insert(book)
  479. relationship := NewRelationship()
  480. relationship.BookId = book.BookId
  481. relationship.RoleId = 0
  482. relationship.MemberId = book.MemberId
  483. relationship.Insert()
  484. err := filepath.Walk(tempPath, func(path string, info os.FileInfo, err error) error {
  485. path = strings.Replace(path, "\\", "/", -1)
  486. if path == tempPath {
  487. return nil
  488. }
  489. if !info.IsDir() {
  490. ext := filepath.Ext(info.Name())
  491. //如果是Markdown文件
  492. if strings.EqualFold(ext, ".md") || strings.EqualFold(ext, ".markdown") {
  493. beego.Info("正在处理 =>",path,info.Name())
  494. doc := NewDocument()
  495. doc.BookId = book.BookId
  496. doc.MemberId = book.MemberId
  497. docIdentify := strings.Replace(strings.TrimPrefix(path, tempPath+"/"), "/", "-", -1)
  498. if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, docIdentify); !ok || err != nil {
  499. docIdentify = "import-" + docIdentify
  500. }
  501. doc.Identify = docIdentify
  502. //匹配图片,如果图片语法是在代码块中,这里同样会处理
  503. re := regexp.MustCompile(`!\[(.*?)\]\((.*?)\)`)
  504. markdown, err := filetil.ReadFileAndIgnoreUTF8BOM(path)
  505. if err != nil {
  506. return err
  507. }
  508. //处理图片
  509. doc.Markdown = re.ReplaceAllStringFunc(string(markdown), func(image string) string {
  510. images := re.FindAllSubmatch([]byte(image), -1)
  511. if len(images) <= 0 || len(images[0]) < 3 {
  512. return image
  513. }
  514. originalImageUrl := string(images[0][2])
  515. imageUrl := strings.Replace(string(originalImageUrl), "\\", "/", -1)
  516. //如果是本地路径,则需要将图片复制到项目目录
  517. if !strings.HasPrefix(imageUrl, "http://") &&
  518. !strings.HasPrefix(imageUrl, "https://") &&
  519. !strings.HasPrefix(imageUrl,"ftp://") {
  520. //如果路径中存在参数
  521. if l := strings.Index(imageUrl,"?"); l > 0 {
  522. imageUrl = imageUrl[:l]
  523. }
  524. if strings.HasPrefix(imageUrl, "/") {
  525. imageUrl = filepath.Join(tempPath, imageUrl)
  526. } else if strings.HasPrefix(imageUrl, "./") {
  527. imageUrl = filepath.Join(filepath.Dir(path), strings.TrimPrefix(imageUrl, "./"))
  528. } else if strings.HasPrefix(imageUrl, "../") {
  529. imageUrl = filepath.Join(filepath.Dir(path), imageUrl)
  530. } else {
  531. imageUrl = filepath.Join(filepath.Dir(path), imageUrl)
  532. }
  533. imageUrl = strings.Replace(imageUrl, "\\", "/", -1)
  534. dstFile := filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), strings.TrimPrefix(imageUrl, tempPath))
  535. if filetil.FileExists(imageUrl) {
  536. filetil.CopyFile(imageUrl, dstFile)
  537. imageUrl = strings.TrimPrefix(strings.Replace(dstFile,"\\","/",-1), strings.Replace(conf.WorkingDirectory,"\\","/",-1))
  538. if !strings.HasPrefix(imageUrl, "/") && !strings.HasPrefix(imageUrl, "\\") {
  539. imageUrl = "/" + imageUrl
  540. }
  541. }
  542. } else {
  543. imageExt := cryptil.Md5Crypt(imageUrl) + filepath.Ext(imageUrl)
  544. dstFile := filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), imageExt)
  545. if err := requests.DownloadAndSaveFile(imageUrl, dstFile); err == nil {
  546. imageUrl = strings.TrimPrefix(strings.Replace(dstFile, "\\", "/", -1), strings.Replace(conf.WorkingDirectory, "\\", "/", -1))
  547. if !strings.HasPrefix(imageUrl, "/") && !strings.HasPrefix(imageUrl, "\\") {
  548. imageUrl = "/" + imageUrl
  549. }
  550. }
  551. }
  552. imageUrl = strings.Replace(strings.TrimSuffix(image, originalImageUrl+")")+ conf.URLForWithCdnImage(imageUrl) +")", "\\", "/", -1)
  553. return imageUrl
  554. })
  555. linkRegexp := regexp.MustCompile(`\[(.*?)\]\((.*?)\)`)
  556. //处理链接
  557. doc.Markdown = linkRegexp.ReplaceAllStringFunc(doc.Markdown, func(link string) string {
  558. links := linkRegexp.FindAllStringSubmatch(link, -1)
  559. originalLink := links[0][2]
  560. var linkPath string
  561. var err error
  562. if strings.HasPrefix(originalLink,"<") {
  563. originalLink = strings.TrimPrefix(originalLink,"<")
  564. }
  565. if strings.HasSuffix(originalLink,">") {
  566. originalLink = strings.TrimSuffix(originalLink,">")
  567. }
  568. //如果是从根目录开始,
  569. if strings.HasPrefix(originalLink, "/") {
  570. linkPath, err = filepath.Abs(filepath.Join(tempPath, originalLink))
  571. } else if strings.HasPrefix(originalLink, "./") {
  572. linkPath, err = filepath.Abs(filepath.Join(filepath.Dir(path), originalLink[1:]))
  573. } else{
  574. linkPath, err = filepath.Abs(filepath.Join(filepath.Dir(path), originalLink))
  575. }
  576. if err == nil {
  577. //如果本地存在该链接
  578. if filetil.FileExists(linkPath) {
  579. ext := filepath.Ext(linkPath)
  580. //beego.Info("当前后缀 -> ",ext)
  581. //如果链接是Markdown文件,则生成文档标识,否则,将目标文件复制到项目目录
  582. if strings.EqualFold(ext, ".md") || strings.EqualFold(ext, ".markdown") {
  583. docIdentify := strings.Replace(strings.TrimPrefix(strings.Replace(linkPath, "\\", "/", -1), tempPath+"/"), "/", "-", -1)
  584. //beego.Info(originalLink, "|", linkPath, "|", docIdentify)
  585. if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, docIdentify); !ok || err != nil {
  586. docIdentify = "import-" + docIdentify
  587. }
  588. docIdentify = strings.TrimSuffix(docIdentify, "-README.md")
  589. link = strings.TrimSuffix(link, originalLink+")") + conf.URLFor("DocumentController.Read", ":key", book.Identify, ":id", docIdentify) + ")"
  590. } else {
  591. dstPath := filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), originalLink)
  592. filetil.CopyFile(linkPath, dstPath)
  593. tempLink := conf.BaseUrl + strings.TrimPrefix(strings.Replace(dstPath, "\\", "/", -1), strings.Replace(conf.WorkingDirectory, "\\", "/", -1))
  594. link = strings.TrimSuffix(link, originalLink+")") + tempLink + ")"
  595. }
  596. }else{
  597. beego.Info("文件不存在 ->",linkPath)
  598. }
  599. }
  600. return link
  601. })
  602. //codeRe := regexp.MustCompile("```\\w+")
  603. //doc.Markdown = codeRe.ReplaceAllStringFunc(doc.Markdown, func(s string) string {
  604. // //beego.Info(s)
  605. // return strings.Replace(s,"```","``` ",-1)
  606. //})
  607. doc.Content = string(blackfriday.Run([]byte(doc.Markdown)))
  608. doc.Version = time.Now().Unix()
  609. //解析文档名称,默认使用第一个h标签为标题
  610. docName := strings.TrimSuffix(info.Name(), ext)
  611. for _, line := range strings.Split(doc.Markdown, "\n") {
  612. if strings.HasPrefix(line, "#") {
  613. docName = strings.TrimLeft(line, "#")
  614. break
  615. }
  616. }
  617. doc.DocumentName = strings.TrimSpace(docName)
  618. parentId := 0
  619. parentIdentify := strings.Replace(strings.Trim(strings.TrimSuffix(strings.TrimPrefix(path, tempPath), info.Name()), "/"), "/", "-", -1)
  620. if parentIdentify != "" {
  621. if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, parentIdentify); !ok || err != nil {
  622. parentIdentify = "import-" + parentIdentify
  623. }
  624. if id, ok := docMap[parentIdentify]; ok {
  625. parentId = id
  626. }
  627. }
  628. if strings.EqualFold(info.Name(), "README.md") {
  629. beego.Info(path, "|", info.Name(), "|", parentIdentify, "|", parentId)
  630. }
  631. isInsert := false
  632. //如果当前文件是README.md,则将内容更新到父级
  633. if strings.EqualFold(info.Name(), "README.md") && parentId != 0 {
  634. doc.DocumentId = parentId
  635. //beego.Info(path,"|",parentId)
  636. } else {
  637. //beego.Info(path,"|",parentIdentify)
  638. doc.ParentId = parentId
  639. isInsert = true
  640. }
  641. if err := doc.InsertOrUpdate("document_name", "markdown", "content"); err != nil {
  642. beego.Error(doc.DocumentId, err)
  643. }
  644. if isInsert {
  645. docMap[docIdentify] = doc.DocumentId
  646. }
  647. }
  648. } else {
  649. //如果当前目录下存在Markdown文件,则需要创建此节点
  650. if filetil.HasFileOfExt(path, []string{".md", ".markdown"}) {
  651. beego.Info("正在处理 =>",path,info.Name())
  652. identify := strings.Replace(strings.Trim(strings.TrimPrefix(path, tempPath), "/"), "/", "-", -1)
  653. if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, identify); !ok || err != nil {
  654. identify = "import-" + identify
  655. }
  656. parentDoc := NewDocument()
  657. parentDoc.MemberId = book.MemberId
  658. parentDoc.BookId = book.BookId
  659. parentDoc.Identify = identify
  660. parentDoc.Version = time.Now().Unix()
  661. parentDoc.DocumentName = "空白文档"
  662. parentId := 0
  663. parentIdentify := strings.TrimSuffix(identify, "-"+info.Name())
  664. if id, ok := docMap[parentIdentify]; ok {
  665. parentId = id
  666. }
  667. parentDoc.ParentId = parentId
  668. if err := parentDoc.InsertOrUpdate(); err != nil {
  669. beego.Error(err)
  670. }
  671. docMap[identify] = parentDoc.DocumentId
  672. //beego.Info(path,"|",parentDoc.DocumentId,"|",identify,"|",info.Name(),"|",parentIdentify)
  673. }
  674. }
  675. return nil
  676. })
  677. if err != nil {
  678. beego.Error("导入项目异常 => ", err)
  679. book.Description = "【项目导入存在错误:" + err.Error() + "】"
  680. }
  681. beego.Info("项目导入完毕 => ", book.BookName)
  682. book.ReleaseContent(book.BookId)
  683. return err
  684. }