diff --git a/Makefile b/Makefile index 38bd61b..fcbccce 100644 --- a/Makefile +++ b/Makefile @@ -24,8 +24,6 @@ TESTS = \ ${GOPKG_PREFIX}/grub_theme/themetxt \ ${GOPKG_PREFIX}/gtk-thumbnailer \ ${GOPKG_PREFIX}/hans2pinyin \ - ${GOPKG_PREFIX}/huangli \ - ${GOPKG_PREFIX}/huangli-generator \ ${GOPKG_PREFIX}/i18n_dependent \ ${GOPKG_PREFIX}/image-blur \ ${GOPKG_PREFIX}/image-blur-helper \ @@ -33,7 +31,6 @@ TESTS = \ ${GOPKG_PREFIX}/lang_info \ ${GOPKG_PREFIX}/language_support \ ${GOPKG_PREFIX}/locale-helper \ - ${GOPKG_PREFIX}/lunar-calendar \ ${GOPKG_PREFIX}/polkit \ ${GOPKG_PREFIX}/powersupply \ ${GOPKG_PREFIX}/powersupply/battery \ @@ -95,7 +92,6 @@ BINARIES = \ adjust-grub-theme \ image-blur \ image-blur-helper - #lunar-calendar \ all: build-binary build-dev ts-to-policy diff --git a/huangli-generator/.gitignore b/huangli-generator/.gitignore deleted file mode 100644 index 1b4ffeb..0000000 --- a/huangli-generator/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -huangli_generator -huangli-generator diff --git a/huangli-generator/Makefile b/huangli-generator/Makefile deleted file mode 100644 index 1e307db..0000000 --- a/huangli-generator/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -PROG=huangli_generator - -build: - go build -o ${PROG} - -clean: - rm -f ${PROG} - -rebuild: clean build diff --git a/huangli-generator/README.org b/huangli-generator/README.org deleted file mode 100644 index ee0117e..0000000 --- a/huangli-generator/README.org +++ /dev/null @@ -1,58 +0,0 @@ -#+OPTIONS: toc:nil num:nil timestamp:nil ^:{} <:{} -#+TITLE: 生成黄历数据 - -** Description - -程序用来生成黄历数据到数据库中,数据爬自百度。 - -经过测试百度中目前(2019)可获取到 =2008.1 ~ 2020.12= 的数据。 - -** Prepare - -设置 =GOPATH= ,如 =mkdir ~/go && export GOPATH=~/go= - -** Dependencies - -*** Build Dependencies - -+ =go= - - =sudo apt-get install golang-src golang-go= - -+ =github.com/mattn/go-sqlite3= - - =go get -u -v github.com/mattn/go-sqlite3= - -+ =libsqlite3-dev= - - =sudo apt-get install libsqlite3-dev= - -*** Run Dependencies - -+ =sqlite3= - - =sudo apt-get install sqlite3= - -** Build - -=make build= - - -** Run - -使用方法请执行: - -=./huangli_generator -h= - -查看 - -** Version - -当前版本为 =v1.0= ,生成的是 =2008.1 ~ 2020.12= 之间的数据,生成的命令如下: - -#+BEGIN_SRC shell -./huangli_generator -s 2008 -e 2020 -f ../misc/data/huangli.db -echo "v1.0" > ../misc/data/huangli.version -#+END_SRC - -*之后更新完数据,必须同时更新 =version= ,否则依然使用的是旧数据* diff --git a/huangli-generator/huangli.db b/huangli-generator/huangli.db deleted file mode 100644 index 719dbd2..0000000 Binary files a/huangli-generator/huangli.db and /dev/null differ diff --git a/huangli-generator/huangliBase.db b/huangli-generator/huangliBase.db deleted file mode 100644 index ec14f88..0000000 Binary files a/huangli-generator/huangliBase.db and /dev/null differ diff --git a/huangli-generator/main.go b/huangli-generator/main.go deleted file mode 100644 index c32f87b..0000000 --- a/huangli-generator/main.go +++ /dev/null @@ -1,146 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package main - -import ( - "flag" - "fmt" - "strconv" - "time" - - "github.com/jinzhu/gorm" - - "github.com/linuxdeepin/dde-api/huangli" -) - -var ( - start = flag.Int("s", 0, "The start year, the min value is 2008") - end = flag.Int("e", 0, "The end year, the max year is (now year) + 1") - festival = flag.Bool("fest", false, "Generate the current year festival db data") - test = flag.Bool("t", false, "Test huangli api") - dbFile = flag.String("f", "huangli.db", "The huangli data sqlite db file") -) - -func main() { - const baseDBFile = "./huangliBase.db" - flag.Parse() - if *test { - doTest() - return - } - - if !*festival && ((*start == 0 && *end == 0) || *end-*start < 0 || *start < 2008 || *end > (time.Now().Year()+20)) { - fmt.Printf("Invalid start year and end year: %d - %d\n", *start, *end) - return - } - - err := huangli.Init(*dbFile) - if err != nil { - panic(err) - } - defer huangli.Finalize() - - db, err := gorm.Open("sqlite3", baseDBFile) - if err != nil { - panic(err) - } - defer func() { - _ = db.Close() - }() - - if *festival { - genFestivalData() - return - } - - // generated db data - genHuangLiData(db, *start, *end) -} - -type Huangli struct { - ID int - Y int // 年 - M int // 月 - D int // 日 - Yi string // 宜 - Ji string // 忌 -} - -func genHuangLiData(db *gorm.DB, start, end int) { - var baseHuangliList []*Huangli - var genHuangliList huangli.HuangLiList - err := db.Where("Y >= ? AND Y <= ?", start, end).Find(&baseHuangliList).Error - if err != nil { - fmt.Println("Failed to get db data:", err) - } - genHuangliList = make(huangli.HuangLiList, 0, 100) - for _, item := range baseHuangliList { - if len(genHuangliList) >= 100 { - err := genHuangliList.Create() - if err != nil { - fmt.Println("Failed to create db data:", err) - return - } - genHuangliList = genHuangliList[0:0:100] - } - temp := &huangli.HuangLi{} - temp.Avoid = item.Ji - temp.Suit = item.Yi - temp.ID, _ = strconv.ParseInt(fmt.Sprintf("%d%02d%02d", item.Y, item.M, item.D), 10, 64) - genHuangliList = append(genHuangliList, temp) - } - err = genHuangliList.Create() - if err != nil { - fmt.Println("Failed to create db data:", err) - return - } -} - -func genFestivalData() { - t := time.Now() - var list huangli.FestivalList - for i := 1; i < 13; i++ { - info, err := newBaiduFestivalByDate(t.Year(), i) - if err != nil { - fmt.Println("Failed to get festival data:", err, t.Year(), i) - return - } - list = append(list, info.ToFestival(t.Year(), i)...) - } - err := list.Create(t.Year()) - if err != nil { - fmt.Println("Failed to create festival:", err) - } -} - -func doTest() { - n := time.Now() - data, err := doGet(makeURL(n.Year(), int(n.Month()))) - if err != nil { - fmt.Println("Failed to get huangli from api:", err) - return - } - info, err := newBaiduHuangLi(data) - if err != nil { - fmt.Println("Failed to unmarshal:", err) - return - } - info.Dump() - - fest, err := newBaiduFestival(data) - if err != nil { - fmt.Println("Failed to unmarshal festival:", err) - return - } - fest.Dump() -} - -func newBaiduFestivalByDate(year, month int) (*baiduFestival, error) { - data, err := doGet(makeURL(year, month)) - if err != nil { - return nil, err - } - return newBaiduFestival(data) -} diff --git a/huangli-generator/request.go b/huangli-generator/request.go deleted file mode 100644 index 4ebd311..0000000 --- a/huangli-generator/request.go +++ /dev/null @@ -1,234 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package main - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/linuxdeepin/dde-api/huangli" -) - -const ( - apiURL = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php" - resourceID = 6018 // 黄历资源 ID - apiCharset = "utf8" -) - -type baiduHuangLi struct { - Data []struct { - Almanac []struct { - Date string `json:"date"` - Avoid string `json:"avoid"` - Suit string `json:"suit"` - } `json:"almanac"` - } `json:"data"` -} - -type baiduFestivalDay struct { - Date string `json:"date"` - Status string `json:"status"` -} - -type baiduFestivalDayList []*baiduFestivalDay - -type baiduFestivalHoliday struct { - Name string `json:"name"` - Festival string `json:"festival"` - Description string `json:"desc"` - Rest string `json:"rest"` - List baiduFestivalDayList `json:"list"` -} - -type baiduFestivalHolidayList []*baiduFestivalHoliday - -type baiduFestivalData struct { - Holiday baiduFestivalHolidayList `json:"holiday"` -} - -type baiduFestivalData2 struct { - Holiday baiduFestivalHoliday `json:"holiday"` -} - -type baiduFestival struct { - Data []*baiduFestivalData `json:"data"` -} - -type baiduFestival2 struct { - Data []*baiduFestivalData2 `json:"data"` -} - -func (info *baiduHuangLi) ToHuangLiList() huangli.HuangLiList { - var list huangli.HuangLiList - for _, almanac := range info.Data { - for _, value := range almanac.Almanac { - id, err := convertDateToID(value.Date) - if err != nil { - fmt.Println("Failed to convert date to id:", err) - continue - } - list = append(list, &huangli.HuangLi{ - ID: id, - Avoid: value.Avoid, - Suit: value.Suit, - }) - } - } - return list -} - -func (info *baiduHuangLi) Dump() { - fmt.Println("Baidu huangli:") - for _, almanac := range info.Data { - for _, value := range almanac.Almanac { - fmt.Printf("\tDate: %q, \tavoid: %q, \tsuit: %q\n", - value.Date, value.Avoid, value.Suit) - } - } - fmt.Println("Baidu huangli dump done") -} - -func (info *baiduFestival) ToFestival(year, month int) huangli.FestivalList { - var list huangli.FestivalList - for _, days := range info.Data { - for _, day := range days.Holiday { - id, err := getFestivalID(day.Festival, month) - if err != nil { - fmt.Println("Failed to convert festival id:", day.Festival, err) - continue - } - yearMonthStr := fmt.Sprintf("%04d%02d", year, month) - if 0 != strings.Index(id, yearMonthStr) { - continue - } - var info = huangli.Festival{ - ID: id, - Month: month, - Name: day.Name, - Description: day.Description, - Rest: day.Rest, - Holidays: day.List.ToHolidayList(), - } - // if !info.Holidays.Contain(year, month) { - // fmt.Println("Not contain year-month:", info.ID, info.Name, year, month) - // continue - // } - list = append(list, &info) - } - } - return list -} - -func (info *baiduFestival) Dump() { - fmt.Println("Baidu festival:") - for _, days := range info.Data { - for _, day := range days.Holiday { - fmt.Printf("\tName: %s, \tFestival: %s, \tDesc: %s, \tRest: %s\n", - day.Name, day.Festival, day.Description, day.Rest) - for _, holiday := range day.List { - fmt.Printf("\t\tDate: %s, \tstatus: %s\n", holiday.Date, holiday.Status) - } - fmt.Println("") - } - } - fmt.Println("Baidu festival dump done") -} - -func (list baiduFestivalDayList) ToHolidayList() huangli.HolidayList { - var holidays huangli.HolidayList - for _, info := range list { - v, err := strconv.Atoi(info.Status) - if err != nil { - fmt.Println("Failed to convert holiday status:", info.Status, err) - continue - } - holidays = append(holidays, &huangli.Holiday{ - Date: info.Date, - Status: huangli.HolidayStatus(v), - }) - } - return holidays -} - -func newBaiduHuangLi(data []byte) (*baiduHuangLi, error) { - var info baiduHuangLi - err := json.Unmarshal(data, &info) - if err != nil { - return nil, err - } - - return &info, nil -} - -func newBaiduFestival(data []byte) (*baiduFestival, error) { - var info baiduFestival - err := json.Unmarshal(data, &info) - if err == nil { - return &info, nil - } - var info2 baiduFestival2 - err = json.Unmarshal(data, &info2) - if err != nil { - return nil, err - } - for i, days := range info2.Data { - info.Data = append(info.Data, &baiduFestivalData{}) - info.Data[i].Holiday = baiduFestivalHolidayList{&days.Holiday} - } - return &info, nil -} - -func doGet(uri string) ([]byte, error) { - resp, err := http.Get(uri) - if err != nil { - return nil, err - } - if resp.Body == nil { - return nil, fmt.Errorf("no data return") - } - defer func() { - _ = resp.Body.Close() - }() - - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("%s", string(data)) - } - return data, nil -} - -func makeURL(year, month int) string { - var params = make(url.Values) - params["resource_id"] = []string{fmt.Sprint(resourceID)} - params["ie"] = []string{apiCharset} - params["oe"] = []string{apiCharset} - params["query"] = []string{fmt.Sprintf("%d年%d月", year, month)} - - return fmt.Sprintf("%s?%s", apiURL, params.Encode()) -} - -func getFestivalID(fest string, month int) (string, error) { - list := strings.SplitN(fest, "-", 3) - if len(list) != 3 { - return "", fmt.Errorf("invalid baidu festival date: %s", fest) - } - return fmt.Sprintf("%s%02s%02s%02d", list[0], list[1], list[2], month), nil -} - -func convertDateToID(date string) (int64, error) { - list := strings.SplitN(date, "-", 3) - if len(list) != 3 { - return 0, fmt.Errorf("invalid baidu huangli date: %s", date) - } - return strconv.ParseInt(fmt.Sprintf("%s%02s%02s", list[0], list[1], list[2]), 10, 64) -} diff --git a/huangli/db.go b/huangli/db.go deleted file mode 100644 index b043b25..0000000 --- a/huangli/db.go +++ /dev/null @@ -1,329 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package huangli - -import ( - "database/sql" - "fmt" - - "time" - - "encoding/json" - - "strings" - - _ "github.com/mattn/go-sqlite3" -) - -// HuangLi huang li info from baidu -type HuangLi struct { - ID int64 `json:"id"` // format: ("%s%02s%02s", year, month, day) - Avoid string `json:"avoid"` - Suit string `json:"suit"` -} - -// HuangLiList huang li info list -type HuangLiList []*HuangLi - -type HolidayStatus int - -const ( - HolidayStatusLeave HolidayStatus = iota + 1 - HolidayStatusWork -) - -type Holiday struct { - Date string `json:"date"` - Status HolidayStatus `json:"status"` -} - -type HolidayList []*Holiday - -func (list HolidayList) Contain(year, month int) bool { - str := fmt.Sprintf("%d-%d-", year, month) - for _, info := range list { - if strings.Contains(info.Date, str) { - return true - } - } - return false -} - -type Festival struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Rest string `json:"rest"` - list string - - Month int `json:"month"` - - Holidays HolidayList `json:"list"` -} - -type FestivalList []*Festival - -var ( - _db *sql.DB -) - -// Init open db and create table -func Init(filename string) error { - var err error - _db, err = sql.Open("sqlite3", filename) - if err != nil { - return err - } - tableStmt := ` -CREATE TABLE IF NOT EXISTS huangli (id INTEGER NOT NULL PRIMARY KEY, avoid TEXT, suit TEXT); -` - _, err = _db.Exec(tableStmt) - if err != nil { - return err - } - return initFestival() -} - -func initFestival() error { - var year = time.Now().Year() - var table = fmt.Sprintf("festival_%d", year) - var tableStmt = fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s ", table) - tableStmt += ` -(id TEXT NOT NULL PRIMARY KEY,month INTEGER NOT NULL,name TEXT,description TEXT, rest TEXT, list TEXT)` - _, err := _db.Exec(tableStmt) - return err -} - -// Finalize close db -func Finalize() { - _ = _db.Close() -} - -// Create insert to sqlite, if exists, ignore -func (list HuangLiList) Create() error { - if len(list) == 0 { - return nil - } - tx, err := _db.Begin() - if err != nil { - return err - } - - for _, info := range list { - tmp, _ := txQueryHuangLi(tx, info.ID) - if tmp != nil { - fmt.Println("Has exists:", tmp.ID, tmp.Avoid, tmp.Suit, info.ID, info.Avoid, info.Suit) - continue - } - err = txCreateHuangLi(tx, info) - if err != nil { - _ = tx.Rollback() - return err - } - } - - return tx.Commit() -} - -func (list FestivalList) Create(year int) error { - var table = fmt.Sprintf("festival_%d", year) - tx, err := _db.Begin() - if err != nil { - return err - } - - for _, info := range list { - tmp, _ := txQueryFestival(tx, table, info.ID) - if tmp != nil { - fmt.Println("Has exists:", tmp.ID, tmp.Name, tmp.Description) - continue - } - err = txCreateFestival(tx, table, info) - if err != nil { - _ = tx.Rollback() - return err - } - } - return tx.Commit() -} - -func (list FestivalList) String() string { - data, _ := json.Marshal(list) - return string(data) -} - -func (info *Festival) EncodeHolidayList() { - info.list = "" - if len(info.Holidays) == 0 { - return - } - data, _ := json.Marshal(info.Holidays) - info.list = string(data) -} - -func (info *Festival) DecodeHolidayList() { - info.Holidays = HolidayList{} - if len(info.list) == 0 { - return - } - _ = json.Unmarshal([]byte(info.list), &info.Holidays) -} - -// NewHuangLi query by id -func NewHuangLi(id int64) (*HuangLi, error) { - return txQueryHuangLi(nil, id) -} - -// NewHuangLiList query by id list -func NewHuangLiList(idList []int64) (HuangLiList, error) { - if len(idList) == 0 { - return nil, nil - } - - tx, err := _db.Begin() - if err != nil { - return nil, err - } - - var list HuangLiList - for _, id := range idList { - info, err := txQueryHuangLi(tx, id) - if err != nil { - // TODO(jouyouyun): warning? - fmt.Println("Failed to query huangli by id:", id, err) - info = &HuangLi{} - } - list = append(list, info) - } - - err = tx.Commit() - if err != nil { - return nil, err - } - return list, nil -} - -func NewFestivalList(year, month int) (FestivalList, error) { - table := fmt.Sprintf("festival_%d", year) - return txQueryFestivalList(nil, table, month) -} - -func txQueryHuangLi(tx *sql.Tx, id int64) (*HuangLi, error) { - var ( - stmt *sql.Stmt - err error - ) - - if tx != nil { - stmt, err = tx.Prepare("SELECT id, avoid, suit FROM huangli WHERE id = ?") - } else { - stmt, err = _db.Prepare("SELECT id, avoid, suit FROM huangli WHERE id = ?") - } - if err != nil { - return nil, err - } - defer func() { - _ = stmt.Close() - }() - - var info HuangLi - err = stmt.QueryRow(id).Scan(&info.ID, &info.Avoid, &info.Suit) - if err != nil { - return nil, err - } - return &info, nil -} - -func txCreateHuangLi(tx *sql.Tx, info *HuangLi) error { - stmt, err := tx.Prepare("INSERT INTO huangli (id,avoid,suit) VALUES (?,?,?)") - if err != nil { - return err - } - defer func() { - _ = stmt.Close() - }() - - _, err = stmt.Exec(info.ID, info.Avoid, info.Suit) - return err -} - -func txQueryFestival(tx *sql.Tx, table, id string) (*Festival, error) { - var ( - stmt *sql.Stmt - err error - ) - str := fmt.Sprintf("SELECT id,month,name,description,rest,list FROM %s WHERE id = ?", - table) - if tx != nil { - stmt, err = tx.Prepare(str) - } else { - stmt, err = _db.Prepare(str) - } - if err != nil { - return nil, err - } - defer func() { - _ = stmt.Close() - }() - - var info Festival - err = stmt.QueryRow(id).Scan(&info.ID, &info.Month, &info.Name, &info.Description, - &info.Rest, &info.list) - if err != nil { - return nil, err - } - info.DecodeHolidayList() - return &info, nil -} - -func txQueryFestivalList(tx *sql.Tx, table string, month int) (FestivalList, error) { - var ( - rows *sql.Rows - err error - ) - str := fmt.Sprintf("SELECT id,month,name,description,rest,list FROM %s WHERE month = %d", - table, month) - if tx != nil { - rows, err = tx.Query(str) - } else { - rows, err = _db.Query(str) - } - if err != nil { - return nil, err - } - defer func() { - _ = rows.Close() - }() - - var list FestivalList - for rows.Next() { - var info Festival - err := rows.Scan(&info.ID, &info.Month, &info.Name, &info.Description, - &info.Rest, &info.list) - if err != nil { - return nil, err - } - info.DecodeHolidayList() - list = append(list, &info) - } - return list, nil -} - -func txCreateFestival(tx *sql.Tx, table string, info *Festival) error { - str := fmt.Sprintf("INSERT INTO %s (id,month,name,description,rest,list) VALUES (?,?,?,?,?,?)", - table) - stmt, err := tx.Prepare(str) - if err != nil { - return err - } - defer func() { - _ = stmt.Close() - }() - - info.EncodeHolidayList() - _, err = stmt.Exec(info.ID, info.Month, info.Name, info.Description, - info.Rest, info.list) - return err -} diff --git a/huangli/db_test.go b/huangli/db_test.go deleted file mode 100644 index 5be4207..0000000 --- a/huangli/db_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package huangli - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestContain(t *testing.T) { - holidayList := HolidayList([]*Holiday{ - { - Date: "2020-12-1", - Status: 0, - }, - { - Date: "2020-12-2", - Status: 0, - }, - { - Date: "2020-11-1", - Status: 0, - }, - }) - tests := []struct { - InputYear int - InputMouth int - Expect bool - }{ - { - InputYear: 2020, - InputMouth: 11, - Expect: true, - }, - { - InputYear: 2020, - InputMouth: 12, - Expect: true, - }, - { - InputYear: 2020, - InputMouth: 9, - Expect: false, - }, - { - InputYear: 2019, - InputMouth: 12, - Expect: false, - }, - } - for _, data := range tests { - assert.Equal(t, data.Expect, holidayList.Contain(data.InputYear, data.InputMouth)) - } -} diff --git a/lunar-calendar/.gitignore b/lunar-calendar/.gitignore deleted file mode 100644 index 73942b4..0000000 --- a/lunar-calendar/.gitignore +++ /dev/null @@ -1 +0,0 @@ -lunar-calendar diff --git a/lunar-calendar/calendar.go b/lunar-calendar/calendar.go deleted file mode 100644 index c6c30f9..0000000 --- a/lunar-calendar/calendar.go +++ /dev/null @@ -1,122 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package main - -import ( - "fmt" - "strconv" - - "github.com/linuxdeepin/go-lib/calendar" - "github.com/linuxdeepin/go-lib/calendar/util" -) - -type DayInfo struct { - Year int32 - Month int32 - Day int32 -} -type DayInfoList []DayInfo - -type LunarMonthInfo struct { - FirstDayWeek int32 - Days int32 - Datas []calendar.LunarDayInfo -} - -type SolarMonthInfo struct { - FirstDayWeek int32 - Days int32 - Datas []DayInfo -} - -/** - * 获取指定公历月份的农历数据 - * year,month 公历年,月 - * fill 是否用上下月数据补齐首尾空缺,首例数据从周日开始 - */ -func getLunarMonthCalendar(year, month int, fill bool) (LunarMonthInfo, SolarMonthInfo, bool) { - solarMonth, ok := getSolarMonthCalendar(year, month, fill) - if !ok { - return LunarMonthInfo{}, SolarMonthInfo{}, false - } - var datas []calendar.LunarDayInfo - for _, data := range solarMonth.Datas { - lunarDay, ok := calendar.SolarToLunar(int(data.Year), int(data.Month), int(data.Day)) - if !ok { - return LunarMonthInfo{}, SolarMonthInfo{}, false - } - datas = append(datas, lunarDay) - } - return LunarMonthInfo{solarMonth.FirstDayWeek, solarMonth.Days, datas}, solarMonth, true -} - -/** - * 公历某月日历 - * year,month 公历年,月 - * fill 是否用上下月数据补齐首尾空缺,首例数据从周日开始(7*6阵列) - */ - -func getSolarMonthCalendar(year, month int, fill bool) (SolarMonthInfo, bool) { - weekday := util.GetWeekday(year, month, 1) - days := util.GetSolarMonthDays(year, month) - // 本月的数据 - daysData := getMonthDays(year, month, 1, days) - if fill { - if weekday > 0 { - preYear, preMonth := getPreMonth(year, month) - // 前一个月的天数 - preDays := util.GetSolarMonthDays(preYear, preMonth) - // 要补充上去的前一个月的数据 - preDaysData := getMonthDays(preYear, preMonth, preDays-weekday+1, preDays) - daysData = append(preDaysData, daysData...) - } - nextYear, nextMonth := getNextMonth(year, month) - count := 6*7 - (weekday + days) - // 要补充上去的下一个月的数据 - nextDaysData := getMonthDays(nextYear, nextMonth, 1, count) - daysData = append(daysData, nextDaysData...) - } - return SolarMonthInfo{int32(weekday), int32(days), daysData}, true -} - -func getMonthDays(year, month, start, end int) []DayInfo { - var list []DayInfo - for day := start; day <= end; day++ { - day := DayInfo{int32(year), int32(month), int32(day)} - list = append(list, day) - } - return list -} - -func getPreMonth(year, month int) (preYear, preMonth int) { - if month == 1 { - preYear = year - 1 - preMonth = 12 - return - } - preYear = year - preMonth = month - 1 - return -} - -func getNextMonth(year, month int) (nextYear, nextMonth int) { - if month == 12 { - nextYear = year + 1 - nextMonth = 1 - return - } - nextYear = year - nextMonth = month + 1 - return -} - -func (days DayInfoList) GetIDList() (list []int64) { - for _, day := range days { - v, _ := strconv.ParseInt(fmt.Sprintf("%d%02d%02d", - day.Year, day.Month, day.Day), 10, 64) - list = append(list, v) - } - return -} diff --git a/lunar-calendar/exported_methods_auto.go b/lunar-calendar/exported_methods_auto.go deleted file mode 100644 index 7e7aecd..0000000 --- a/lunar-calendar/exported_methods_auto.go +++ /dev/null @@ -1,48 +0,0 @@ -// Code generated by "dbusutil-gen em -type Manager"; DO NOT EDIT. - -package main - -import ( - "github.com/linuxdeepin/go-lib/dbusutil" -) - -func (v *Manager) GetExportedMethods() dbusutil.ExportedMethods { - return dbusutil.ExportedMethods{ - { - Name: "GetFestivalMonth", - Fn: v.GetFestivalMonth, - InArgs: []string{"year", "month"}, - OutArgs: []string{"jsonStr"}, - }, - { - Name: "GetFestivalsInRange", - Fn: v.GetFestivalsInRange, - InArgs: []string{"start", "end"}, - OutArgs: []string{"result"}, - }, - { - Name: "GetHuangLiDay", - Fn: v.GetHuangLiDay, - InArgs: []string{"year", "month", "day"}, - OutArgs: []string{"jsonStr"}, - }, - { - Name: "GetHuangLiMonth", - Fn: v.GetHuangLiMonth, - InArgs: []string{"year", "month", "fill"}, - OutArgs: []string{"jsonStr"}, - }, - { - Name: "GetLunarInfoBySolar", - Fn: v.GetLunarInfoBySolar, - InArgs: []string{"year", "month", "day"}, - OutArgs: []string{"lunarDay", "ok"}, - }, - { - Name: "GetLunarMonthCalendar", - Fn: v.GetLunarMonthCalendar, - InArgs: []string{"year", "month", "fill"}, - OutArgs: []string{"lunarMonth", "ok"}, - }, - } -} diff --git a/lunar-calendar/huangli.go b/lunar-calendar/huangli.go deleted file mode 100644 index bd3694a..0000000 --- a/lunar-calendar/huangli.go +++ /dev/null @@ -1,134 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package main - -import ( - "encoding/json" - "path/filepath" - - "os" - - "io/ioutil" - - "github.com/linuxdeepin/dde-api/huangli" - "github.com/linuxdeepin/go-lib/calendar" - "github.com/linuxdeepin/go-lib/utils" - "github.com/linuxdeepin/go-lib/xdg/basedir" -) - -// HuangLiInfo huang li -type HuangLiInfo struct { - calendar.LunarDayInfo - Avoid string - Suit string -} - -// HuangLiInfoList huang li list -type HuangLiInfoList []*HuangLiInfo - -// HuangLiMonthInfo huang li month info -type HuangLiMonthInfo struct { - FirstDayWeek int32 - Days int32 - Datas HuangLiInfoList -} - -const ( - defaultHuangLiDBFile = "/usr/share/dde-api/data/huangli.db" - defaultHuangLiVerFile = "/usr/share/dde-api/data/huangli.version" -) - -var ( - _hasHuangLi bool -) - -func initHuangLi() { - err := huangli.Init(getDBFile()) - if err != nil { - logger.Error("Failed to open huangli db:", err) - _hasHuangLi = false - return - } - _hasHuangLi = true -} - -func finalizeHuangLi() { - huangli.Finalize() -} - -// String json marshal -func (info *HuangLiInfo) String() string { - data, _ := json.Marshal(info) - return string(data) -} - -// String json marshal -func (info *HuangLiMonthInfo) String() string { - data, _ := json.Marshal(info) - return string(data) -} - -func newHuangLiInfoList(lunarDays []calendar.LunarDayInfo, days DayInfoList) (list HuangLiInfoList) { - var infos huangli.HuangLiList - if _hasHuangLi { - infos, _ = huangli.NewHuangLiList(days.GetIDList()) - } else { - for i := 0; i < len(lunarDays); i++ { - infos = append(infos, &huangli.HuangLi{}) - } - } - for i := 0; i < len(lunarDays); i++ { - list = append(list, &HuangLiInfo{ - LunarDayInfo: lunarDays[i], - Avoid: infos[i].Avoid, - Suit: infos[i].Suit, - }) - } - return -} - -func newFestivalList(year, month int) (huangli.FestivalList, error) { - return huangli.NewFestivalList(year, month) -} - -func getDBFile() string { - filename := filepath.Join(basedir.GetUserConfigDir(), "deepin", "dde-api", "huangli.db") - if utils.IsFileExist(filename) && checkDBVersion() { - return filename - } - - err := os.MkdirAll(filepath.Dir(filename), 0755) - if err != nil { - logger.Warning("Failed to mkdir for huangli db:", err) - } else { - err := utils.CopyFile(defaultHuangLiDBFile, filename) - if err != nil { - logger.Warning("Failed to copy huangli db file:", err) - } - versionFile := filepath.Join(basedir.GetUserConfigDir(), "deepin", "dde-api", "huangli.version") - err = utils.CopyFile(defaultHuangLiVerFile, versionFile) - if err != nil { - logger.Warning("Failed to copy huangli version file:", err) - } - } - return filename - -} - -func checkDBVersion() bool { - filename := filepath.Join(basedir.GetUserConfigDir(), "deepin", "dde-api", "huangli.version") - if !utils.IsFileExist(filename) { - return false - } - src, err := ioutil.ReadFile(defaultHuangLiVerFile) - if err != nil { - return false - } - dest, err := ioutil.ReadFile(filename) - if err != nil { - return false - } - return string(src) == string(dest) -} diff --git a/lunar-calendar/lunar_calendar_test.go b/lunar-calendar/lunar_calendar_test.go deleted file mode 100644 index 3037e64..0000000 --- a/lunar-calendar/lunar_calendar_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package main - -import ( - "fmt" - "testing" - - "github.com/linuxdeepin/go-lib/dbusutil" - "github.com/stretchr/testify/suite" -) - -type UnitTestSuite struct { - suite.Suite - m *Manager -} - -func (s *UnitTestSuite) SetupSuite() { - var err error - s.m = &Manager{} - s.m.service, err = dbusutil.NewSessionService() - if err != nil { - s.T().Skip(fmt.Sprintf("failed to get service: %v", err)) - } -} - -func (s *UnitTestSuite) Test_GetInterfaceName() { - s.m.GetInterfaceName() -} - -func (s *UnitTestSuite) Test_GetLunarInfoBySolar() { - _, _, err := s.m.GetLunarInfoBySolar(2021, 10, 1) - s.Require().Nil(err) -} - -func (s *UnitTestSuite) Test_GetFestivalsInRange() { - _, err := s.m.GetFestivalsInRange("2021-01-02", "2021-10-01") - s.Require().Nil(err) -} - -func (s *UnitTestSuite) Test_GetLunarMonthCalendar() { - _, _, err := s.m.GetLunarMonthCalendar(2021, 10, true) - s.Require().Nil(err) -} - -func (s *UnitTestSuite) Test_GetHuangLiDay() { - _, err := s.m.GetHuangLiDay(2021, 10, 1) - s.Require().Nil(err) -} - -func (s *UnitTestSuite) Test_GetHuangLiMonth() { - _, err := s.m.GetHuangLiMonth(2021, 10, true) - s.Require().Nil(err) -} - -func TestUnitTestSuite(t *testing.T) { - suite.Run(t, new(UnitTestSuite)) -} diff --git a/lunar-calendar/main.go b/lunar-calendar/main.go deleted file mode 100644 index c00beed..0000000 --- a/lunar-calendar/main.go +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package main - -import ( - "time" - - "github.com/linuxdeepin/go-lib/dbusutil" - "github.com/linuxdeepin/go-lib/log" -) - -var ( - logger = log.NewLogger("api/LunarCalendar") -) - -func main() { - logger.SetRestartCommand("/usr/lib/deepin-api/lunar-calendar") - - service, err := dbusutil.NewSessionService() - if err != nil { - logger.Fatal("failed to new session service:", err) - } - - hasOwner, err := service.NameHasOwner(dbusServiceName) - if err != nil { - logger.Fatal(err) - } - if hasOwner { - logger.Fatalf("name %q already has the owner", dbusServiceName) - } - - initHuangLi() - defer finalizeHuangLi() - - m := NewManager(service) - err = service.Export(dbusPath, m) - if err != nil { - logger.Fatal("failed to export:", err) - } - - err = service.RequestName(dbusServiceName) - if err != nil { - logger.Fatal("failed to request name:", err) - } - - service.SetAutoQuitHandler(time.Second*100, nil) - service.Wait() -} diff --git a/lunar-calendar/manager.go b/lunar-calendar/manager.go deleted file mode 100644 index 676df67..0000000 --- a/lunar-calendar/manager.go +++ /dev/null @@ -1,159 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -package main - -import ( - "errors" - "fmt" - "strings" - - "github.com/godbus/dbus/v5" - "github.com/linuxdeepin/go-lib/calendar" - "github.com/linuxdeepin/go-lib/calendar/lunar" - "github.com/linuxdeepin/go-lib/dbusutil" - libdate "github.com/rickb777/date" -) - -//go:generate dbusutil-gen em -type Manager - -const ( - dbusServiceName = "org.deepin.dde.LunarCalendar1" - dbusPath = "/org/deepin/dde/LunarCalendar1" - dbusInterface = "org.deepin.dde.LunarCalendar1" -) - -type Manager struct { - service *dbusutil.Service -} - -func (*Manager) GetInterfaceName() string { - return dbusInterface -} - -func NewManager(service *dbusutil.Service) *Manager { - return &Manager{ - service: service, - } -} - -// GetLunarInfoBySolar 获取指定公历日期的农历信息 -// year 公历年 -// month 公历月 -// day 公历日 -func (m *Manager) GetLunarInfoBySolar(year, month, day int32) (lunarDay calendar.LunarDayInfo, ok bool, busErr *dbus.Error) { - m.service.DelayAutoQuit() - if info, ok := calendar.SolarToLunar(int(year), int(month), int(day)); !ok { - return calendar.LunarDayInfo{}, false, nil - } else { - return info, true, nil - } -} - -type DayFestival struct { - Year int32 - Month int32 - Day int32 - Festivals []string -} - -func (m *Manager) GetFestivalsInRange(start, end string) (result []DayFestival, busErr *dbus.Error) { - m.service.DelayAutoQuit() - - startDate, err := libdate.ParseISO(start) - if err != nil { - return nil, dbusutil.ToError(err) - } - endDate, err := libdate.ParseISO(end) - if err != nil { - return nil, dbusutil.ToError(err) - } - if startDate.After(endDate) { - return nil, dbusutil.ToError(errors.New("start date after end date")) - } - date := startDate - for !date.After(endDate) { - // date <= endDate - cal := lunar.New(date.Year()) - lunarDay := cal.SolarDayToLunarDay(int(date.Month()), date.Day()) - var festivals []string - festival := lunarDay.Festival() - if festival != "" { - festivals = append(festivals, festival) - } - solarDay := calendar.Day{Year: date.Year(), Month: int(date.Month()), Day: date.Day()} - festival = solarDay.Festival() - if festival != "" { - parts := strings.Split(festival, ",") - festivals = append(festivals, parts...) - } - if len(festivals) > 0 { - //logger.Debugf("date: %s, festivals: %v", date, festivals) - result = append(result, DayFestival{ - Year: int32(solarDay.Year), - Month: int32(solarDay.Month), - Day: int32(solarDay.Day), - Festivals: festivals, - }) - } - date = date.Add(1) - } - return result, nil -} - -// GetLunarMonthCalendar 获取指定指定公历月份的农历信息 -// 第一项数据从周日开始 -// year 公历年 -// month 公历月 -// fill 是否用上下月数据补齐首尾空缺 -func (m *Manager) GetLunarMonthCalendar(year, month int32, fill bool) (lunarMonth LunarMonthInfo, ok bool, busErr *dbus.Error) { - m.service.DelayAutoQuit() - logger.Debugf("LUNAR DATE: %v %v %v", year, month, fill) - if info, _, ok := getLunarMonthCalendar(int(year), int(month), fill); !ok { - return LunarMonthInfo{}, false, nil - } else { - logger.Debugf("Lunar Month Data: %v", info) - return info, true, nil - } -} - -// GetHuangLiDay 获取指定公历日的黄历信息 -func (m *Manager) GetHuangLiDay(year, month, day int32) (jsonStr string, busErr *dbus.Error) { - m.service.DelayAutoQuit() - info, ok := calendar.SolarToLunar(int(year), int(month), int(day)) - if !ok { - return "", dbusutil.ToError(fmt.Errorf("invalid date: %d-%d-%d", year, month, day)) - } - list := newHuangLiInfoList([]calendar.LunarDayInfo{info}, DayInfoList{DayInfo{ - Year: year, - Month: month, - Day: day, - }}) - return list[0].String(), nil -} - -// GetHuangLiMonth 获取指定公历月的黄历信息 -func (m *Manager) GetHuangLiMonth(year, month int32, fill bool) (jsonStr string, busErr *dbus.Error) { - m.service.DelayAutoQuit() - lunarDays, solarDays, ok := getLunarMonthCalendar(int(year), int(month), fill) - if !ok { - return "", dbusutil.ToError(fmt.Errorf("invalid date: %d-%d", year, month)) - } - list := newHuangLiInfoList(lunarDays.Datas, solarDays.Datas) - var ret = HuangLiMonthInfo{ - FirstDayWeek: lunarDays.FirstDayWeek, - Days: lunarDays.Days, - Datas: list, - } - return ret.String(), nil -} - -// GetFestivalMonth 获取指定公历月的假日信息 -func (m *Manager) GetFestivalMonth(year, month int) (jsonStr string, busErr *dbus.Error) { - list, err := newFestivalList(year, month) - if err != nil { - return "", dbusutil.ToError(err) - } - return list.String(), nil -} diff --git a/rpm/dde-api.spec b/rpm/dde-api.spec index 8c58bb2..09b5b6b 100644 --- a/rpm/dde-api.spec +++ b/rpm/dde-api.spec @@ -118,8 +118,6 @@ exit 0 %{_datadir}/dbus-1/system-services/*.service %{_datadir}/dbus-1/system.d/*.conf %{_datadir}/icons/hicolor/*/actions/* -%{_datadir}/dde-api/data/huangli.db -%{_datadir}/dde-api/data/huangli.version %{_datadir}/dde-api/data/pkg_depends %{_datadir}/dde-api/data/grub-themes/ %{_datadir}/polkit-1/actions/org.deepin.dde.locale-helper.policy