code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
package com.infindo.appcreate.zzyj.dao;
import com.infindo.appcreate.zzyj.entity.SysUser;
public interface UserDao extends GenericDao<SysUser, Long> {
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/dao/UserDao.java
|
Java
|
gpl3
| 163
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.infindo.appcreate.zzyj.util.DateTimeUtil;
@Entity
@Table(name = "zzyj_activity_talk", schema = "public")
public class ActivityTalk implements java.io.Serializable {
private static final long serialVersionUID = -961556270368780758L;
private Long id;
private String actCode;
private String expertCode;//public or expert code
private String image;
private String nickName;
private Date time;
private String desc;
private String timeF;//format time item
public ActivityTalk(){
}
public ActivityTalk(String actCode, String expertCode, String image, String nickName, Date time, String desc){
super();
this.actCode = actCode;
this.expertCode = expertCode;
this.image = image;
this.nickName = nickName;
this.time = time;
this.desc = desc;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_activity_talk",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "_desc")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Column(name = "time")
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Column(name = "act_code")
public String getActCode() {
return actCode;
}
public void setActCode(String actCode) {
this.actCode = actCode;
}
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Column(name = "nickName")
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Column(name = "expert_code")
public String getExpertCode() {
return expertCode;
}
public void setExpertCode(String expertCode) {
this.expertCode = expertCode;
}
@Transient
public String getTimeF() {
if(null != this.time){
return DateTimeUtil.DateToString("yyyy.MM.dd hh:mm:ss", this.time);
}
return null;
}
public void setTimeF(String timeF) {
this.timeF = timeF;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/ActivityTalk.java
|
Java
|
gpl3
| 2,982
|
package com.infindo.appcreate.zzyj.entity;
// Generated 2012-11-12 16:59:05 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.SEQUENCE;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* SysUser generated by hbm2java
*/
@Entity
@Table(name = "sys_user", schema = "public")
public class SysUser implements java.io.Serializable {
private Long id;
private String account;
private String passwd;
private String nickName;
private String phone;
private String im;
private Integer status;
private Date updateTime;
@SequenceGenerator(name = "generator", sequenceName = "sys_user_seq",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "account", length = 250)
public String getAccount() {
return this.account;
}
public void setAccount(String account) {
this.account = account;
}
@Column(name = "passwd", length = 250)
public String getPasswd() {
return this.passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
@Column(name = "nick_name", length = 250)
public String getNickName() {
return this.nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Column(name = "phone", length = 250)
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name = "im", length = 250)
public String getIm() {
return this.im;
}
public void setIm(String im) {
this.im = im;
}
@Column(name = "status")
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "update_time", length = 29)
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/SysUser.java
|
Java
|
gpl3
| 2,527
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "zzyj_service", schema = "public")
public class Service implements java.io.Serializable {
private static final long serialVersionUID = 8299608566293726476L;
private Long id;
private String image;
private String title;
private String organ;
private String desc;
private String declInforms;//多个 dot 隔开, 声明通知
private String opeDetails;//多个 dot 隔开,操作细节
private String declVideos;//多个 dot 隔开,声明视频
public Service(){}
public Service(String image, String title, String organ, String desc, String declInforms, String opeDetails, String declVideos){
super();
this.image = image;
this.title = title;
this.organ = organ;
this.desc = desc;
this.declInforms = declInforms;
this.opeDetails = opeDetails;
this.declVideos = declVideos;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_service",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Column(name = "title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "organ")
public String getOrgan() {
return organ;
}
public void setOrgan(String organ) {
this.organ = organ;
}
@Column(name = "decl_informs")
public String getDeclInforms() {
return declInforms;
}
public void setDeclInforms(String declInforms) {
this.declInforms = declInforms;
}
@Column(name = "ope_details")
public String getOpeDetails() {
return opeDetails;
}
public void setOpeDetails(String opeDetails) {
this.opeDetails = opeDetails;
}
@Column(name = "decl_videos")
public String getDeclVideos() {
return declVideos;
}
public void setDeclVideos(String declVideos) {
this.declVideos = declVideos;
}
@Column(name = "_desc")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/Service.java
|
Java
|
gpl3
| 2,944
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.infindo.appcreate.zzyj.util.DateTimeUtil;
@Entity
@Table(name = "zzyj_project_supporter", schema = "public")
public class ProjectSupporter implements java.io.Serializable {
private static final long serialVersionUID = -6794704141714707380L;
private Long id;
private String projectCode;
private String expertCode;
private Date time;
private Integer score;
private Integer type;//0 expert; 1 public;
private String image;//
private String authIcon;
private String nickName;
private String timeF;//format time item
public ProjectSupporter(){}
public ProjectSupporter(String projectCode, String expertCode, Date time, Integer score, Integer type, String image, String authIcon, String nickName){
super();
this.projectCode = projectCode;
this.expertCode = expertCode;
this.time = time;
this.score = score;
this.type = type;
this.image = image;
this.authIcon = authIcon;
this.nickName = nickName;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_project_supporter",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "project_code")
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
@Column(name = "expert_code")
public String getExpertCode() {
return expertCode;
}
public void setExpertCode(String expertCode) {
this.expertCode = expertCode;
}
@Column(name = "time")
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Column(name = "score")
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Column(name = "type")
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Column(name = "auth_icon")
public String getAuthIcon() {
return authIcon;
}
public void setAuthIcon(String authIcon) {
this.authIcon = authIcon;
}
@Column(name = "nick_name")
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Transient
public String getTimeF() {
if(null != this.time){
return DateTimeUtil.DateToString("yyyy.MM.dd hh:mm:ss", this.time);
}
return null;
}
public void setTimeF(String timeF) {
this.timeF = timeF;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/ProjectSupporter.java
|
Java
|
gpl3
| 3,565
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "zzyj_expert", schema = "public")
public class Expert implements java.io.Serializable {
private static final long serialVersionUID = -3973101546052955127L;
private Long id;
private String code;
private String name;
private String image;
private String desc;
private String authIcon;//专家认证图标 V
private Integer authIconType;//0 blue v; 1 yellow v;
private String weiBo;
public Expert(){
}
public Expert( String code, String name, String image, String desc, String authIcon, String weiBo){
super();
this.code = code;
this.name = name;
this.image = image;
this.desc = desc;
this.authIcon = authIcon;
this.weiBo = weiBo;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_expert",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "_desc")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Column(name = "auth_icon")
public String getAuthIcon() {
return authIcon;
}
public void setAuthIcon(String authIcon) {
this.authIcon = authIcon;
}
@Column(name = "weibo")
public String getWeiBo() {
return weiBo;
}
public void setWeiBo(String weiBo) {
this.weiBo = weiBo;
}
@Column(name = "auth_icon_type")
public Integer getAuthIconType() {
return authIconType;
}
public void setAuthIconType(Integer authIconType) {
this.authIconType = authIconType;
}
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/Expert.java
|
Java
|
gpl3
| 2,730
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.infindo.appcreate.zzyj.util.DateTimeUtil;
@Entity
@Table(name = "zzyj_project_comment", schema = "public")
public class ProjectComment implements java.io.Serializable {
private static final long serialVersionUID = 4078996767329716910L;
private Long id;
private String projectCode;
private String expertCode;
private Date time;
private String desc;
private Integer type;//0 expert; 1 public
private String image;//
private String authIcon;
private String nickName;
private String timeF;//format time item
public ProjectComment(){}
public ProjectComment(String projectCode, String expertCode, Date time, String desc, Integer type, String image, String authIcon, String nickName){
super();
this.projectCode = projectCode;
this.expertCode = expertCode;
this.time = time;
this.desc = desc;
this.type = type;
this.image = image;
this.authIcon = authIcon;
this.nickName = nickName;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_project_comment",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "project_code")
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
@Column(name = "expert_code")
public String getExpertCode() {
return expertCode;
}
public void setExpertCode(String expertCode) {
this.expertCode = expertCode;
}
@Column(name = "time")
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Column(name = "_desc")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Column(name = "type")
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Column(name = "auth_icon")
public String getAuthIcon() {
return authIcon;
}
public void setAuthIcon(String authIcon) {
this.authIcon = authIcon;
}
@Column(name = "nick_name")
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Transient
public String getTimeF() {
if(null != this.time){
return DateTimeUtil.DateToString("yyyy.MM.dd", this.time);
}
return null;
}
public void setTimeF(String timeF) {
this.timeF = timeF;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/ProjectComment.java
|
Java
|
gpl3
| 3,535
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "zzyj_expert_project", schema = "public")
public class ExpertProject implements java.io.Serializable {
private static final long serialVersionUID = -2671929235195624804L;
private Long id;
private String expertCode;
private String projectCode;
private Integer type;//0 支持的; 1 发起的
public ExpertProject(){
}
public ExpertProject(String expertCode, String projectCode, Integer type){
super();
this.expertCode = expertCode;
this.projectCode = projectCode;
this.type = type;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_expert_project",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "expert_code")
public String getExpertCode() {
return expertCode;
}
public void setExpertCode(String expertCode) {
this.expertCode = expertCode;
}
@Column(name = "project_code")
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
@Column(name = "type")
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/ExpertProject.java
|
Java
|
gpl3
| 1,879
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.infindo.appcreate.zzyj.util.DateTimeUtil;
@Entity
@Table(name = "zzyj_infomation", schema = "public")
public class Infomation implements java.io.Serializable {
private static final long serialVersionUID = 6872734083870332220L;
private Long id;
private Long code;
private String title;
private String image;
private String origin;
private Date time;
private String desc;
private String timeF;//format time item
public Infomation(){}
public Infomation(Long code, String title, String image, String origin, Date time, String desc){
super();
this.code = code;
this.title = title;
this.image = image;
this.origin = origin;
this.time = time;
this.desc = desc;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_infomation",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "code")
public Long getCode() {
return code;
}
public void setCode(Long code) {
this.code = code;
}
@Column(name = "_desc")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Column(name = "title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "origin")
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
@Column(name = "time")
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Transient
public String getTimeF() {
if(null != this.time){
return DateTimeUtil.DateToString("yyyy.MM.dd", this.time);
}
return null;
}
public void setTimeF(String timeF) {
this.timeF = timeF;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/Infomation.java
|
Java
|
gpl3
| 2,801
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "zzyj_project_hot", schema = "public")
public class ProjectHot implements java.io.Serializable {
private static final long serialVersionUID = 6952792461269745128L;
private Long id;
private String projectCode;
public ProjectHot(){}
public ProjectHot(String projectCode){
super();
this.projectCode = projectCode;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_project_hot",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "project_code")
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/ProjectHot.java
|
Java
|
gpl3
| 1,292
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.Transient;
import com.infindo.appcreate.zzyj.util.DateTimeUtil;
import com.infindo.appcreate.zzyj.util.StringUtil;
@Entity
@Table(name = "zzyj_project", schema = "public")
public class Project implements java.io.Serializable {
private static final long serialVersionUID = 5836568984239431729L;
private Long id;
private String code;
private String title;
private Date time;
private String timeF;//format time item
private String user;
private String place;
private Integer score;
private Integer expertScore;
private Integer crowdScore;
private String listImage;
//private String imagesSmall;
private String promoteImages;
//private String imagesBig;//no used
private Integer promoteType;//0 image; 1 video
private String desc;//contents contains tags
private String descImage;//no used
public Project(){
}
public Project(String code, String title, Date time, String user, String place, Integer expertScore, Integer score,
Integer crowdScore, String listImage, String promoteImages, Integer promoteType, String desc){
super();
this.code = code;
this.title = title;
this.time = time;
this.user = user;
this.place = place;
this.score = score;
this.expertScore = expertScore;
this.crowdScore = crowdScore;
this.listImage = listImage;
this.promoteImages = promoteImages;
this.promoteType = promoteType;
this.desc = desc;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_project",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(name = "title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "time")
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Column(name = "_user")
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
@Column(name = "place")
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
@Column(name = "expert_score")
public Integer getExpertScore() {
return expertScore;
}
public void setExpertScore(Integer expertScore) {
this.expertScore = expertScore;
}
@Column(name = "crowd_score")
public Integer getCrowdScore() {
return crowdScore;
}
public void setCrowdScore(Integer crowdScore) {
this.crowdScore = crowdScore;
}
@Column(name = "list_image")
public String getListImage() {
return listImage;
}
public void setListImage(String listImage) {
this.listImage = listImage;
}
@Column(name = "promote_images")
public String getPromoteImages() {
return promoteImages;
}
public void setPromoteImages(String promoteImages) {
this.promoteImages = promoteImages;
}
@Column(name = "_desc")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Column(name = "desc_image")
public String getDescImage() {
return descImage;
}
public void setDescImage(String descImage) {
this.descImage = descImage;
}
@Column(name = "promote_type")
public Integer getPromoteType() {
return promoteType;
}
public void setPromoteType(Integer promoteType) {
this.promoteType = promoteType;
}
@Column(name = "score")
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Transient
public String getTimeF() {
if(null != this.time){
return DateTimeUtil.DateToString("yyyy-MM-dd", this.time);
}
return null;
}
public void setTimeF(String timeF) {
this.timeF = timeF;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/Project.java
|
Java
|
gpl3
| 5,062
|
package com.infindo.appcreate.zzyj.entity;
public class ExpertCommentVO implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String projectCode;
private String projectTitle;
private String desc;
public ExpertCommentVO(){}
public ExpertCommentVO(String projectCode ,String projectTitle, String desc){
super();
this.projectCode = projectCode;
this.projectTitle = projectTitle;
this.desc = desc;
}
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getProjectTitle() {
return projectTitle;
}
public void setProjectTitle(String projectTitle) {
this.projectTitle = projectTitle;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/ExpertCommentVO.java
|
Java
|
gpl3
| 1,029
|
package com.infindo.appcreate.zzyj.entity;
import static javax.persistence.GenerationType.SEQUENCE;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.infindo.appcreate.zzyj.util.DateTimeUtil;
@Entity
@Table(name = "zzyj_activity", schema = "public")
public class Activity implements java.io.Serializable {
private static final long serialVersionUID = -961556270368780758L;
private Long id;
private String code;
private String title;
private Date time;
private String address;
private String image;//for list
private String images;
private String desc;
private String timeF;//format time item
public Activity(){
}
public Activity(String code, String title, Date time, String address, String image, String images, String desc){
super();
this.code = code;
this.title = title;
this.time = time;
this.address = address;
this.image = image;
this.images = images;
this.desc = desc;
}
@SequenceGenerator(name = "generator", sequenceName = "seq_zzyj_activity",allocationSize=1)
@Id
@GeneratedValue(strategy = SEQUENCE, generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(name = "_desc")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Column(name = "images")
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
@Column(name = "title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "time")
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Transient
public String getTimeF() {
if(null != this.time){
return DateTimeUtil.DateToString("yyyy.MM.dd hh:mm", this.time);
}
return null;
}
public void setTimeF(String timeF) {
this.timeF = timeF;
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/zzyj/entity/Activity.java
|
Java
|
gpl3
| 3,101
|
package com.infindo.appcreate.thread.queue;
public interface ThreadCallback {
public void notifyThreadEnd(long threadNo);
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/thread/queue/ThreadCallback.java
|
Java
|
gpl3
| 134
|
package com.infindo.appcreate.thread.queue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ThreadManager<T> extends Thread implements ThreadCallback {
private int maxThread = 2;
private Map<Long, TaskThread> threadActiveList = new HashMap<Long, TaskThread>();
private List<T> taskList;
private static ThreadManager instance = null;
private boolean running = true;
private boolean taskExecuting = false;
public synchronized static <T> ThreadManager<T> getInstance(T t) {
if (instance == null) {
instance = new ThreadManager<T>();
instance.start();
}
return instance;
}
public void setMaxThread(int threadCount) {
maxThread = threadCount;
}
private ThreadManager() {
}
public boolean isTaskExecuting() {
if (taskList == null || taskList.isEmpty()) {
if (threadActiveList == null || threadActiveList.isEmpty()) {
taskExecuting = false;
}
}
return taskExecuting;
}
public synchronized void addTask(T task) {
if (taskList == null)
taskList = new ArrayList<T>();
taskList.add(task);
notifyMe();
}
public synchronized void addAllTask(List<T> taskList) {
this.taskList = taskList;
notifyMe();
}
private synchronized void notifyMe() {
this.notify();
}
public void run() {
synchronized(this) {
while (running) {
try {
taskExecuting = true;
if (taskList == null || taskList.isEmpty()) {
if (threadActiveList.size() == 0) {
taskExecuting = false;
System.out.println("++++==============all task ended or no task start yet!");
}
this.wait();
} else {
if (threadActiveList.size() >= maxThread) {
this.wait();
} else {
try {
T r = taskList.get(0);
taskList.remove(0);
TaskThread taskThread = new TaskThread (this, r);
threadActiveList.put(taskThread.getId(), taskThread);
taskThread.start();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("threadActiveList.size() " + threadActiveList.size());
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void stopThreadManager() {
running = false;
notifyMe();
}
@Override
public synchronized void notifyThreadEnd(long threadNo) {
TaskThread taskThread = threadActiveList.get(Long.valueOf(threadNo));
if(taskThread != null){
threadActiveList.remove(Long.valueOf(threadNo));
}
notifyMe();
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/thread/queue/ThreadManager.java
|
Java
|
gpl3
| 3,635
|
package com.infindo.appcreate.thread.queue;
import java.lang.reflect.Field;
import com.infindo.appcreate.zzyj.util.StringUtil;
import com.infindo.appcreate.zzyj.util.ThreadGroupEnum;
public class TaskThread<T> extends Thread {
private final ThreadCallback callback;
private T myTask;
public TaskThread(ThreadCallback callback, T myTask) {
this.callback = callback;
this.myTask = myTask;
}
public synchronized void run() {
try {
Field fieldGroupName = myTask.getClass().getField("groupName");
String groupName = (String)fieldGroupName.get(myTask);
if(StringUtil.isNotBlank(groupName) && groupName.equals(ThreadGroupEnum.build.toString())){
myTask.getClass().getMethod("taskRun", null).invoke(myTask, null);
}else if(StringUtil.isBlank(groupName)){
myTask.getClass().getMethod("executeTask", null).invoke(myTask, null);
}
System.out.println("======TaskThread " + getId() + " End");
} catch (Exception e) {
e.printStackTrace();
} finally {
callback.notifyThreadEnd(getId());
}
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/thread/queue/TaskThread.java
|
Java
|
gpl3
| 1,090
|
package com.infindo.appcreate.thread.queue;
public abstract class BaseTask {
public String groupName = "";
public abstract Object executeTask() throws Exception;
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/src/com/infindo/appcreate/thread/queue/BaseTask.java
|
Java
|
gpl3
| 183
|
// Generated on 2013-09-05 using generator-ember 0.6.2
'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// show elapsed time at the end
require('time-grunt')(grunt);
// load all grunt tasks
require('load-grunt-tasks')(grunt);
// configurable paths
var yeomanConfig = {
app: 'app',
dist: 'dist'
};
grunt.initConfig({
yeoman: yeomanConfig,
watch: {
emberTemplates: {
files: '<%= yeoman.app %>/templates/**/*.hbs',
tasks: ['emberTemplates']
},
compass: {
files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['compass:server']
},
neuter: {
files: ['<%= yeoman.app %>/scripts/**/*.js'],
tasks: ['neuter']
},
livereload: {
options: {
livereload: LIVERELOAD_PORT
},
files: [
'.tmp/scripts/*.js',
'<%= yeoman.app %>/*.html',
'{.tmp,<%= yeoman.app %>}/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app)
];
}
}
},
test: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, '.tmp'),
mountFolder(connect, 'test')
];
}
}
},
dist: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, yeomanConfig.dist)
];
}
}
}
},
open: {
server: {
path: 'http://localhost:<%= connect.options.port %>'
}
},
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*'
]
}]
},
server: '.tmp'
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js',
'!<%= yeoman.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
mocha: {
all: {
options: {
run: true,
urls: ['http://localhost:<%= connect.options.port %>/index.html']
}
}
},
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles',
cssDir: '<%= yeoman.app %>/styles',
generatedImagesDir: '.tmp/images/generated',
imagesDir: '<%= yeoman.app %>/images',
javascriptsDir: '<%= yeoman.app %>/scripts',
fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: 'app/bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: true
},
dist: {},
server: {
options: {
debugInfo: true
}
}
},
// not used since Uglify task does concat,
// but still available if needed
/*concat: {
dist: {}
},*/
// not enabled since usemin task does concat and uglify
// check index.html to edit your build targets
// enable this task if you prefer defining your build targets here
/*uglify: {
dist: {}
},*/
rev: {
dist: {
files: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
//'<%= yeoman.dist %>/images/**/*.{png,jpg,jpeg,gif,webp}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
}
},
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>'
}
},
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
dirs: ['<%= yeoman.dist %>']
}
},
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '**/*.{png,jpg,jpeg}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
cssmin: {
dist: {
options: {
keepSpecialComments: 0
},
files: {
'<%= yeoman.dist %>/styles/main.css': [
'<%= yeoman.dist %>/styles/**/*.css'
]
}
}
},
htmlmin: {
dist: {
options: {
/*removeCommentsFromCDATA: true,
// https://github.com/yeoman/grunt-usemin/issues/44
//collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeOptionalTags: true*/
},
files: [{
expand: true,
cwd: '<%= yeoman.app %>',
src: '*.html',
dest: '<%= yeoman.dist %>'
}]
}
},
// Put files not handled in other tasks here
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,txt}',
'.htaccess',
'images/{,*/}*.{webp,gif}'
]
},
{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>/bower_components/font-awesome',
dest: '<%= yeoman.dist %>',
src: [
'font/**'
]
}]
}
},
concurrent: {
server: [
'emberTemplates',
'compass:server'
],
test: [
'emberTemplates',
'compass'
],
dist: [
'emberTemplates',
'compass:dist',
'imagemin',
'svgmin',
'htmlmin'
]
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
emberTemplates: {
options: {
templateName: function (sourceFile) {
var templatePath = yeomanConfig.app + '/templates/';
return sourceFile.replace(templatePath, '');
}
},
dist: {
files: {
'.tmp/scripts/compiled-templates.js': '<%= yeoman.app %>/templates/{,*/}*.hbs'
}
}
},
neuter: {
app: {
options: {
filepathTransform: function (filepath) {
return 'app/' + filepath;
}
},
src: '<%= yeoman.app %>/scripts/index.js',
dest: '.tmp/scripts/combined-scripts.js'
}
}
});
grunt.registerTask('server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'concurrent:server',
'neuter:app',
'connect:livereload',
'open',
'watch'
]);
});
grunt.registerTask('test', [
'clean:server',
'concurrent:test',
'connect:test',
'neuter:app',
'mocha'
]);
grunt.registerTask('build', [
'clean:dist',
'useminPrepare',
'concurrent:dist',
'neuter:app',
'concat',
'cssmin',
'uglify',
'copy',
'rev',
'usemin'
]);
grunt.registerTask('default', [
'jshint',
'test',
'build'
]);
};
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/Gruntfile.js
|
JavaScript
|
gpl3
| 10,968
|
grunt build
grunt watch
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/watchAfterBuild.bat
|
Batchfile
|
gpl3
| 24
|
@charset "utf-8";
/* CSS Document */
.main_title_bg{ background:url(images/main_title_bg.png) repeat-x;}
.column_bg{ background:url(images/column_bg.png) repeat-x;}
.list_details_bg{ background:#efefef;}
.pull_down_top_bg{ background:url(images/pull_down_top.png) no-repeat;}
.pull_down_middle_bg{ background:url(images/pull_down_middle.png) repeat-y;}
.pull_down_bottom_bg{ background:url(images/pull_down_bottom.png) no-repeat;}
.main_title_font{ font-size:36px; color:#FFF;}
.slider_font{ font-size:16px; font-weight:700; color:#FFF;}
.column_font{ font-size:16px; font-weight:800; color:#fff;}
.column_words_title_font{font-size:18px; font-weight:800; }
.footer_font_blue{font-size:16px; font-weight:800; color:#248dbe; }
#footer p{color:#5d5d5d;}
.pull_down_words_font{ font-size:16px; font-weight:800; color:#FFF;}
.red_color{ color:#F00;}
.white_color_bg{ background:#FFF;}
.border{ border-bottom:1px solid #efefef;}
.border_dashed{ border-bottom:1px dashed #909090;}
.fontsize16{ font-size:16px;}
.strong{ font-weight:800;}
.professor_name{ font-size:18px; font-weight:800; color:#5d5d5d;}
.overview_details{ font-size:14px;}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/skin/skin.css
|
CSS
|
gpl3
| 1,155
|
window.Zzyj = Ember.Application.create();
require('scripts/utils/**');
require('scripts/controllers/**');
require('scripts/store');
require('scripts/models/**');
require('scripts/views/**');
require('scripts/router');
require('scripts/routes/**');
$.cookie.defaults = { expires: 7, path: '/', domain: "localhost" };
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/index.js
|
JavaScript
|
gpl3
| 329
|
Zzyj.ApplicationView = Em.View.extend({
templateName: 'application'
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/views/application.js
|
JavaScript
|
gpl3
| 79
|
Zzyj.FooterView = Em.View.extend({
templateName: 'footer'
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/views/footer.js
|
JavaScript
|
gpl3
| 69
|
Zzyj.ProjectsView = Em.View.extend({
templateName: 'project/list',
didInsertElement: function() {
},
handler: function() {
}.observes('controller.content.isLoaded')
});
Zzyj.ProjectView = Em.View.extend({
templateName: 'project/detail',
didInsertElement: function() {
window.mySwipe = Swipe(document.getElementById('slider'),
{
startSlide: 0,
speed: 400,
auto: 1000,
//continuous: true,
disableScroll: false,
stopPropagation: false,
callback: function(index, elem) {},
transitionEnd: function(index, elem) {}
}
);
}
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/views/project.js
|
JavaScript
|
gpl3
| 757
|
Zzyj.HomeView = Em.View.extend({
templateName: 'home',
didInsertElement: function() {
window.mySwipe = Swipe(document.getElementById('slider'),
{
startSlide: 0,
speed: 400,
auto: 1000,
//continuous: true,
disableScroll: false,
stopPropagation: false,
callback: function(index, elem) {},
transitionEnd: function(index, elem) {}
}
);
},
handler: function() {
}.observes('controller.content.isLoaded')
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/views/home.js
|
JavaScript
|
gpl3
| 623
|
Zzyj.HeaderView = Em.View.extend({
templateName: 'header',
didInsertElement: function() {
$('.main_title_icon_right').click(function(){
var menu = $('.pull_down');
if (menu.css("display") == "none") {
menu.fadeIn();
} else {
menu.fadeOut();
}
});
}
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/views/header.js
|
JavaScript
|
gpl3
| 381
|
Zzyj.ExpertsView = Em.View.extend({
templateName: 'expert/list',
didInsertElement: function() {
},
handler: function() {
}.observes('controller.content.isLoaded')
});
Zzyj.ExpertView = Em.View.extend({
templateName: 'expert/detail',
didInsertElement: function() {
// window.mySwipe = Swipe(document.getElementById('slider'),
// {
// startSlide: 0,
// speed: 400,
// auto: 1000,
// //continuous: true,
// disableScroll: false,
// stopPropagation: false,
// callback: function(index, elem) {},
// transitionEnd: function(index, elem) {}
// }
// );
}
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/views/expert.js
|
JavaScript
|
gpl3
| 777
|
Zzyj.Router.map(function () {
this.resource('index', { path: '/'});
this.resource('home', { path: '/home'});
this.resource('projects', { path: '/projects' }, function() {
});
this.resource('project', { path: 'project' }, function() { // /:project_id
// this.route('edit', { path: 'edit' });
//
// this.resource('cms', { path: 'cms' }, function() {
//
// });
});
this.resource('experts', { path: '/experts' }, function() {
});
this.resource('expert', { path: 'expert' }, function() { // /:project_id
});
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/router.js
|
JavaScript
|
gpl3
| 593
|
Zzyj.ApplicationController = Em.Controller.extend({
actions: {
showProjects: function() {
this.transitionToRoute("projects");
$('.pull_down').hide();
Nav.resetBackIcon();
},
showExperts: function() {
this.transitionToRoute("experts");
$('.pull_down').hide();
Nav.resetBackIcon();
},
back: function() {
Nav.back(this);
}
}
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/controllers/application.js
|
JavaScript
|
gpl3
| 483
|
Zzyj.ProjectsController = Em.Controller.extend({
actions: {
showProjectDetail: function(app) {
this.transitionToRoute("project");
Nav.page('projects', '项目');
}
}
});
Zzyj.ProjectController = Em.Controller.extend({
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/controllers/project.js
|
JavaScript
|
gpl3
| 282
|
Zzyj.HomeController = Em.Controller.extend({
actions: {
}
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/controllers/home.js
|
JavaScript
|
gpl3
| 76
|
Zzyj.ExpertsController = Em.Controller.extend({
actions: {
showExpertDetail: function(app) {
this.transitionToRoute("expert");
Nav.page('experts', '专家');
}
}
});
Zzyj.ExpertController = Em.Controller.extend({
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/controllers/expert.js
|
JavaScript
|
gpl3
| 277
|
Custant = {
ApiVer: 'v1'
};
if (location.href.indexOf("192.168") > -1) {
Custant.WebRoot = "http://192.168.1.228:9000/";
} else {
Custant.WebRoot = "http://121.199.18.199/";
}
Vari = {
ApiPath: Custant.WebRoot + "api/" + Custant.ApiVer + "/",
TokenName: "apppress.token",
CurrUser: {id: null},
CurrApp: null,
CurrAction: null,
DragType: null,
srcId: null
};
Util = {
isEmpty: function (o){
if (o == null || o== "null" || o == undefined || o == "undefined" || o == "") {
return true;
} else {
return false;
}
},
isNotEmpty: function (o){
return !Util.isEmpty(o);
},
handleInput: function (){
return false;
},
getUrlParam: function(pname) {
var rt = '';
var url = unescape(window.location.href);
url = url.split('#')[0];
var allArgs = url.split("?")[1];
if (!allArgs) {
return '';
}
var args = allArgs.split("&");
for(var i=0; i<args.length; i++) {
var arg = args[i].split("=");
if (arg[0] == pname) {
//console.log('find url param: ' + arg[0]+'="'+arg[1]+'";');
rt = arg[1];
return rt;
}
}
return rt;
},
addHeadLink : function(rel, href) {
var head = document.getElementsByTagName("head")[0];
var link = document.createElement('link');
link.setAttribute('rel', rel);
link.setAttribute('href', href);
head.appendChild(link);
},
removeHeadLink: function(rel, href) {
var links=document.getElementsByTagName('link');
for (var i=0; i<links.length; i++) {
//console.log(links[i].rel+ ', ' + links[i].href);
if ( links[i].rel == rel &&
links[i].href.indexOf(href) > -1) {
links[i].parentNode.removeChild(links[i]);
}
}
},
getIndexPath: function() {
var arr = location.href.split("?");
delete arr[arr.length-1];
var dir = arr.join("");
return dir;
},
getDocSize: function() {
var sh = window.screen.height;
if (document.body.clientHeight > sh) {
sh = document.body.clientHeight;
}
var sw = window.screen.width;
if (document.body.clientWidth > sw) {
sw = document.body.clientWidth;
}
return {h: sh, w:sw};
},
capFirstLetter: function (word){
var w = word.substring(0,1).toUpperCase() + word.substring(1);
return w;
},
lowFirstLetter: function (word){
var w = word.substring(0,1).toLowerCase() + word.substring(1);
return w;
}
};
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/utils/util.js
|
JavaScript
|
gpl3
| 2,583
|
Handlebars.registerHelper('vari', function(v) {
if (Util.isEmpty(v))
return "";
var value = eval('Vari.' + v);
//alert(value);
return new Handlebars.SafeString(value);
});
Handlebars.registerHelper('first', function(context, block) {
return context[0];
});
Handlebars.registerHelper('reqPath', function(uri) {
if (Util.isEmpty(uri))
return new Handlebars.SafeString(Vari.ApiPath);
var url = Vari.ApiPath + uri;
return new Handlebars.SafeString(url);
});
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
operator = options.hash.operator || "==";
constant = options.hash.constant || true;
lvalue = Ember.get(this, lvalue);
if (operator != 'typeof') {
if (!constant)
rvalue = Ember.get(this, rvalue);
}
var operators = {
'==' : function(l, r) {
return l == r;
},
'===' : function(l, r) {
return l === r;
},
'!=' : function(l, r) {
return l != r;
},
'<' : function(l, r) {
return l < r;
},
'>' : function(l, r) {
return l > r;
},
'<=' : function(l, r) {
return l <= r;
},
'>=' : function(l, r) {
return l >= r;
},
'typeof' : function(l, r) {
return typeof l == r;
}
};
if (!operators[operator])
throw new Error(
"Handlerbars Helper 'compare' doesn't know the operator "
+ operator);
var result = operators[operator](lvalue, rvalue);
//alert(lvalue + "," + rvalue);
if (result) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Handlebars.registerHelper("breadcrumb",function(arr, options) {
arr = Ember.get(this, arr);
var html = '<ul class="breadcrumb">';
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (i === arr.length -1) {
html += '<li class="active">' + item.label + '</li>';
} else {
html += '<li><a href="#">' + item.label + '</a> <span class="divider">/</span></li>';
}
}
html += '</ul>';
return new Handlebars.SafeString(html);
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/utils/helpers.js
|
JavaScript
|
gpl3
| 2,201
|
Nav = {
page: function (route, title){
$('main_title').text(title);
Nav.history.push([route, title]);
Nav.showBackIconOrNot();
},
back: function (controller){
$('main_title').text(title);
if (Nav.history.length > 0) {
var arr = Nav.history.pop();
var route = arr[0];
var title = arr[1];
controller.transitionToRoute(route, {main: 'slideRight'});
$('main_title').text(title);
}
Nav.showBackIconOrNot();
},
showBackIconOrNot: function() {
if (Nav.history.length > 0) {
$('.main_title_icon_left').show();
} else {
$('.main_title_icon_left').hide();
}
},
resetBackIcon: function() {
Nav.history = [];
Nav.showBackIconOrNot();
},
history: []
};
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/utils/nav.js
|
JavaScript
|
gpl3
| 884
|
Zzyj.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('home');
Nav.page('home', '众智云集');
}
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/routes/index.js
|
JavaScript
|
gpl3
| 156
|
Zzyj.ProjectsRoute = Ember.Route.extend({
model: function(params) {
},
setupController: function(controller) {
// var list = controller.store.find('app');
// controller.set('model', list);
}
});
Zzyj.ProjectRoute = Ember.Route.extend({
// model: function(params) {
// if (Util.isNotEmpty(params.project_id)) {
// var project = this.store.find('project', params.project_id);
// return project;
// }
// },
// setupController: function(controller, project) {
// controller.set('model', project);
// }
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/routes/project.js
|
JavaScript
|
gpl3
| 612
|
Zzyj.HomeRoute = Ember.Route.extend({
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/routes/home.js
|
JavaScript
|
gpl3
| 46
|
Zzyj.ApplicationRoute = Ember.Route.extend({
actions: {
}
});
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/scripts/routes/application_route.js
|
JavaScript
|
gpl3
| 78
|
<!--content-->
<div id="content_wrapper">
<div class="content_top">
<div id='slider' class='swipe'>
<div class='swipe-wrap'>
<div class="item" style="background:url(images/img1.png) no-repeat center 0;-moz-background-size: cover;background-size: cover;">
<span class="slider_font">2013年度“扶持引导社会力量参与苏州工业...”</span>
</div>
<div class="item" style="background:url(images/img2.png) no-repeat center 0;-moz-background-size: cover;background-size: cover;">
<span class="slider_font">2013年度“扶持引导社会力量参与苏州工业...”</span>
</div>
</div>
</div>
</div>
<div class="content_column clearfix">
<div class="column_title column_bg">
<p class="column_font">
最新项目<img src="skin/images/new.png">
</p>
</div>
<div class="column_details clearfix">
<div class="list_item_image float_left">
<img src="images/img2.png">
</div>
<div class="column_words">
<p class="column_words_title column_words_title_font">园区市民卡手机信息服务平台</p>
<span class="column_words_details column_words_details_font">“掌上社区”是一款基于地图的社区信息推送、居民信息反馈采集的移动应用。应用结合三...[详细]</span>
</div>
</div>
</div>
<div class="content_column clearfix">
<div class="column_title column_bg">
<p class="column_font">
最新项目<img src="skin/images/new.png">
</p>
</div>
<div class="column_details clearfix">
<div class="list_item_image float_right">
<img src="images/img2.png">
</div>
<div class="column_words">
<p class="column_words_title column_words_title_font">园区市民卡手机信息服务平台</p>
<span class="column_words_details column_words_details_font">“掌上社区”是一款基于地图的社区信息推送、居民信息反馈采集的移动应用。应用结合三...[详细]</span>
</div>
</div>
</div>
<div class="content_column clearfix">
<div class="column_title column_bg">
<p class="column_font">
最新项目<img src="skin/images/new.png">
</p>
</div>
<div class="column_details clearfix">
<div class="list_item_image float_left">
<img src="images/img2.png">
</div>
<div class="column_words">
<p class="column_words_title column_words_title_font">园区市民卡手机信息服务平台</p>
<span class="column_words_details column_words_details_font">“掌上社区”是一款基于地图的社区信息推送、居民信息反馈采集的移动应用。应用结合三...[详细]</span>
</div>
</div>
</div>
</div>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/templates/home.hbs
|
Handlebars
|
gpl3
| 2,784
|
<!--content-->
<div class="column_details clearfix">
<div class="list_item_image float_left"><img src="images/img4.png"></div>
<div class="column_words">
<div style="height: 50px;">
<p class="professor_name">姚建军<img class="big_v" src="images/v.png"><span class="date">2013-09-27 22:19:00</span></p>
</div>
<div>
<p class="support">
自我介绍:东南大学硕士,有4项中国专利,曾获得第十届挑战杯全国大学生课外学术科技作品竞赛一等奖,参与过多个无线传感器网络和物联网科技项目的研发. 微博:http://weibo.com/alex17swim
</p>
</div>
</div>
</div>
<ul class="content_column clearfix">
<li>
<div class="column_title column_bg"><p class="column_font">支持的项目</p></div>
<ul>
<li class="column_details border_dashed clearfix">
<div class="list_item_image float_left"><img src="images/img2.png"></div>
<div class="column_words"><p class="column_words_title column_words_title_font">园区市民卡手机信息服务平台</p><span class="column_words_details ">“掌上社区”是一款基于地图的社区信息推送、居民信息反馈采集的移动应用。应用结合三...[详细]</span></div>
</li>
</ul>
</li>
<li>
<div class="column_title column_bg"><p class="column_font">发起的项目</p></div>
<ul>
<li class="column_details border_dashed clearfix">
<div class="list_item_image float_left"><img src="images/img2.png"></div>
<div class="column_words"><p class="column_words_title column_words_title_font">园区市民卡手机信息服务平台</p><span class="column_words_details ">“掌上社区”是一款基于地图的社区信息推送、居民信息反馈采集的移动应用。应用结合三...[详细]</span></div>
</li>
</ul>
</li>
<li>
<div class="column_title column_bg"><p class="column_font">发起的点评</p></div>
<ul>
<li class="column_details border_dashed clearfix">
<div class="column_words"><p class="fontsize16 strong">项目名称:中网云计算服务器系统平台</p><span class="fontsize16"><strong>点评内容:</strong>这个云才是真的云计算,云计算必须具备:资源池,弹性...这个云才是真的云计算,云计算必须具备:资源池,弹性...这个云才是真的云计算,云计算必须具备:资源池,弹性...[详细]</span></div>
</li>
</ul>
</li>
</ul>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/templates/expert/detail.hbs
|
Handlebars
|
gpl3
| 2,714
|
<ul class="content_list">
<li {{action showExpertDetail}}>
<div class="column_details border margin_bottom clearfix">
<div class="list_item_image float_left"><img src="images/img4.png"></div>
<div class="column_words">
<div style="height: 50px;">
<p class="professor_name">姚建军<img class="big_v" src="images/v.png"><span class="date">2013-09-27 22:19:00</span></p>
</div>
<div>
<p class="support">中国联通苏州分公司 副总经理 中国联通3G全业务品牌“沃”,代表的是想象力释放带来的无限惊喜……[详细]</p>
</div>
</div>
</div>
</li>
</ul>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/templates/expert/list.hbs
|
Handlebars
|
gpl3
| 784
|
{{view Zzyj.HeaderView}}
<div>
<div class="container-fluid">
{{outlet}}
</div>
</div>
{{view Zzyj.FooterView}}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/templates/application.hbs
|
Handlebars
|
gpl3
| 140
|
<!--footer-->
<div id="footer">
<ul >
<li class="footer_font_blue"><a href="">安卓版</a></li>
<li class="footer_font_blue">|</li>
<li class="footer_font_blue"><a href="">Ios版</a></li>
<li class="footer_font_blue">|</li>
<li class="footer_font_blue"><a href="">wap版</a></li>
<li class="footer_font_blue">|</li>
<li class="footer_font_blue"><a href="">触平板</a></li>
</ul>
<p>Copyright © 众智云集 版权所有</p>
<p>苏ICP备12053611号-1</p>
<p>服务热线:0512-89167102</p>
</div>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/templates/footer.hbs
|
Handlebars
|
gpl3
| 590
|
<!--content-->
<div class="content_top">
<div id='slider' class='swipe'>
<div class='swipe-wrap'>
<div class="item" style="background:url(images/img1.png) no-repeat center 0;-moz-background-size: cover;background-size: cover;">
<span class="slider_font">2013年度“扶持引导社会力量参与苏州工业...”</span>
</div>
<div class="item" style="background:url(images/img2.png) no-repeat center 0;-moz-background-size: cover;background-size: cover;">
<span class="slider_font">2013年度“扶持引导社会力量参与苏州工业...”</span>
</div>
</div>
</div>
</div>
<div class="details_content_overview">
<p class="overview_title"><strong>外脑数字神经系统管理软件</strong></p>
<p class="overview_details"><span>支持得分:<strong class="red_color">59</strong> 分</span><span> 专家<em class="red_color"> 0 </em>人</span><span>|</span><span>公众<em class="red_color"> 59</em> 人</span></p>
<p class="overview_details">发布人:苏州外脑智能科技有限公司</p>
<p class="overview_details">发起地: 江苏省 . 苏州</p>
<p class="overview_details">时间:2013-09-23</p>
</div>
<ul class="content_column clearfix">
<li>
<div class="column_title column_bg"><p class="column_font">项目介绍</p></div>
<div class="column_details auto_height clearfix">
<div class="column_words">
<p class="column_words_details column_words_details_font">外脑数字神经系统简介<br/>
外脑数字神经系统管理软件,是模拟人类神经系统的结构和功能,以岗位为功能划分单位,对企业进行全面信息化管理的新一代智能工具。是新的管理思想、方法和技术。<br/>
外脑软件把企业看作是一个象人一样的有生命的完整个体,而员工是这个个体的组成细胞。外脑的基本结构和功能单位是岗位,岗位是外脑的数字神经细胞,外脑是由岗位细胞组成的一个有生命的完整的个体。企业中的员工和外脑中的岗位一一对应,员工在企业中的功能和作用,通过岗位的功能划分和实现来体现出来。<br/>
外脑软件将各行业的一些基本岗位和机构抽象归纳出来,形成一个企业标准模型,就象人体模型一样,来作为企业管理的研究对象和标准。并在此基础上推出了一系列高度细分化的各行业管理模型,供企事业单位直接应用。外脑数字神经系统管理理论的基础是企业生 命论,具体详见和合先生著《数字神经系统管理原理》一书</p>
<div class="content_image float_left"><img src="images/img3.png"></div>
</div>
</div>
</li>
</ul>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/templates/project/detail.hbs
|
Handlebars
|
gpl3
| 2,942
|
<!--menu-->
<div id="menu">
<ul>
<li class="menu_nav menu_active"><a href="#">时间</a><img src="skin/images/triangle.png"></li>
<li class="menu_nav "><a href="#">得分</a><img src="skin/images/triangle.png"></li>
<li class="menu_nav" ><a href="#">专家</a><img src="skin/images/triangle.png"></li>
<li class="menu_nav"><a href="#">公众</a><img src="skin/images/triangle.png"></li>
<li class="menu_nav"><a href="#">热门</a><img src="skin/images/triangle.png"></li>
</ul>
</div>
<!--content-->
<div id="content_wrapper">
<ul class="content_list">
<li class="list_details" {{action showProjectDetail}}>
<div class="column_details list_details_bg clearfix">
<div class="list_item_image float_left"><img src="images/img2.png"></div>
<div class="column_words">
<p class="column_words_title column_words_title_font">园区市民卡手机信息服务平台</p>
<span class="column_words_details column_words_details_font">"掌上社区"是一款基于地图的社区信息推送、居民信息反馈采集的移动应用。应用结合三...[详细]</span>
</div>
</div>
<div class="dashed"></div>
</li>
</ul>
</div>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/templates/project/list.hbs
|
Handlebars
|
gpl3
| 1,338
|
<!--header-->
<div id="header" >
<div class="main_title_container main_title_bg">
<div class="main_title_icon_left" style="display:none;" {{action back}}><img src="skin/icon/back.png"></div>
<span class="main_title main_title_font">众智云集</span>
<div class="main_title_icon_right">
<img src="skin/icon/add_icon.png">
</div>
</div>
<div class="pull_down" style="display:none;">
<div class="pull_down_top pull_down_top_bg"></div>
<ul class="pull_down_content pull_down_middle_bg">
<li class="pull_down_words pull_down_words_font" {{action showProjects .}}>项目</li>
<li class="pull_down_line"></li>
<li class="pull_down_words pull_down_words_font">服务</li>
<li class="pull_down_line"></li>
<li class="pull_down_words pull_down_words_font" {{action showExperts .}}>专家</li>
<li class="pull_down_line"></li>
<li class="pull_down_words pull_down_words_font">活动</li>
<li class="pull_down_line"></li>
<li class="pull_down_words pull_down_words_font">资讯</li>
</ul>
<div class="pull_down_bottom pull_down_bottom_bg"></div>
</div>
</div>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/templates/header.hbs
|
Handlebars
|
gpl3
| 1,273
|
@charset "UTF-8";
@import url("../skin/skin.css");
/* CSS Document */
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\000034}}
html, body, h1, h2, h3, h4, h5, h6, p, form, dl, dt, dd, ul, li, ol, img, input, select, div, table, tr, td, thead, tbody, p {
border: 0;
font-family: Arial, sans-serif "微软雅黑";
margin: 0;
padding: 0;
font-size: 12px;
color: #5d5d5d;
word-wrap: break-word;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000314}}
em {
font-style: normal;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000315}}
html, body {
height: 100%;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000318}}
ul {
list-style-type: none;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000321}}
a {
text-decoration: none;
color: #0088cc;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000325}}
a:hover, a:focus {
color: #005580;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000328}}
.clearfix:before, .clearfix:after {
content: "";
display: table;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000332}}
.clearfix:after {
clear: both;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000335}}
.clearfix {
*zoom: 1;
/*ie6,7*/
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000339}}
.float_left {
float: left;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/global\.scss}line{font-family:\0000340}}
.float_right {
float: right;
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/styles/global.css
|
CSS
|
gpl3
| 2,551
|
#main_container {
width: 100%;
}
#header {
width: 100%;
height: 71px;
}
.main_title_container {
height: 71px;
text-align: center;
position: relative;
z-index: 1;
}
.main_title {
line-height: 70px;
}
.main_title_icon_right {
position: absolute;
top: 10px;
right: 10px;
}
.main_title_icon_left {
position: absolute;
top: 10px;
left: 10px;
}
.pull_down {
position: absolute;
z-index: 2;
width: 94px;
height: 50px;
right: 10px;
top: 60px;
}
.pull_down_top {
width: 94px;
height: 20px;
}
.pull_down_bottom {
width: 94px;
height: 10px;
}
.pull_down_content .pull_down_words {
text-align: center;
line-height: 50px;
cursor: pointer;
}
.pull_down_line {
width: 90%;
height: 1px;
background: #FFF;
margin: 0 auto;
}
#content_wrapper {
width: 100%;
height: auto;
margin-top: -3px;
}
.content_column {
width: 100%;
height: auto;
}
.column_title {
width: 100%;
height: 40px;
}
.column_title p {
line-height: 40px;
text-indent: 10px;
}
.column_title p img {
position: relative;
bottom: 10px;
left: 5px;
}
.column_details {
width: 100%;
height: auto;
}
.list_item_image, .content_image {
margin: 6px;
}
.content_image, .content_image img {
max-width: 100%;
}
@media only screen and (max-device-width : 499px) {
.list_item_image, .list_item_image img {
width: 150px;
height: 150px;
}
}
@media only screen and (min-device-width : 600px) and (max-device-width : 799px) {
.list_item_image, .list_item_image img {
width: 150px;
height: 150px;
}
}
@media only screen and (min-device-width : 800px) {
.list_item_image, .list_item_image img {
width: 250px;
height: 200px;
}
}
.column_details .column_words {
line-height: 22px;
margin: 10px;
}
#footer {
width: 100%;
height: 100px;
border-top: 1px solid #d2d2d2;
text-align: center;
background: #f5f5f5;
padding-top: 20px;
}
#footer ul {
line-height: 24px;
}
#footer ul li {
display: inline;
}
/*list*/
#menu ul {
width: 100%;
height: 40px;
text-align: center;
background: #efefef;
}
#menu ul li {
display: inline;
line-height: 40px;
font-size: 16px;
margin: 0 10px 0 10px;
}
.menu_nav img {
position: relative;
vertical-align: bottom;
right: 21px;
visibility: hidden;
}
.menu_active a {
color: #333333;
}
.menu_active img {
visibility: visible;
}
.content_list {
width: 100%;
}
.content_list .list_details {
margin: 10px;
}
.dashed {
width: 100%;
height: 1px;
border-bottom: 1px dashed #5d5d5d;
margin-top: 10px;
}
/*detail*/
.details_content_overview {
margin: 10px 0 10px 10px;
line-height: 24px;
}
.overview_title {
font-size: 18px;
}
.details_content_overview .overview_details span {
margin-right: 10px;
}
.user_name {
line-height: 30px;
font-size: 16px;
}
.big_v {
margin-left: 10px;
}
.support {
font-size: 16px;
}
.date {
float: right;
font-size: 12px;
font-weight: 500;
color: #d4d4d4;
}
.margin_bottom {
margin-bottom: 10px;
}
.swipe {
overflow: hidden;
visibility: hidden;
position: relative;
.swipe-wrap {
overflow : hidden;
position: relative;
.item {
float : left;
width: 100%;
position: relative;
height: 251px;
text-align: left;
span.slider_font {
width : 100%;
height: 50px;
line-height: 50px;
text-align: left;
text-indent: 10px;
position: absolute;
z-index: 10;
bottom: 0;
background: #333333;
opacity: .45;
filter: alpha(opacity = 45);
}
img {
}
}
}
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/styles/style.scss
|
SCSS
|
gpl3
| 3,898
|
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\000031}}
#main_container {
width: 100%;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\000035}}
#header {
width: 100%;
height: 71px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000310}}
.main_title_container {
height: 71px;
text-align: center;
position: relative;
z-index: 1;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000317}}
.main_title {
line-height: 70px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000321}}
.main_title_icon_right {
position: absolute;
top: 10px;
right: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000327}}
.main_title_icon_left {
position: absolute;
top: 10px;
left: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000333}}
.pull_down {
position: absolute;
z-index: 2;
width: 94px;
height: 50px;
right: 10px;
top: 60px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000342}}
.pull_down_top {
width: 94px;
height: 20px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000347}}
.pull_down_bottom {
width: 94px;
height: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000352}}
.pull_down_content .pull_down_words {
text-align: center;
line-height: 50px;
cursor: pointer;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000358}}
.pull_down_line {
width: 90%;
height: 1px;
background: #FFF;
margin: 0 auto;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000365}}
#content_wrapper {
width: 100%;
height: auto;
margin-top: -3px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000371}}
.content_column {
width: 100%;
height: auto;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000376}}
.column_title {
width: 100%;
height: 40px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000381}}
.column_title p {
line-height: 40px;
text-indent: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000386}}
.column_title p img {
position: relative;
bottom: 10px;
left: 5px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000392}}
.column_details {
width: 100%;
height: auto;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\0000397}}
.list_item_image, .content_image {
margin: 6px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003100}}
.content_image, .content_image img {
max-width: 100%;
}
@media only screen and (max-device-width: 499px) {
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003104}}
.list_item_image, .list_item_image img {
width: 150px;
height: 150px;
}
}
@media only screen and (min-device-width: 600px) and (max-device-width: 799px) {
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003110}}
.list_item_image, .list_item_image img {
width: 150px;
height: 150px;
}
}
@media only screen and (min-device-width: 800px) {
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003117}}
.list_item_image, .list_item_image img {
width: 250px;
height: 200px;
}
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003123}}
.column_details .column_words {
line-height: 22px;
margin: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003128}}
#footer {
width: 100%;
height: 100px;
border-top: 1px solid #d2d2d2;
text-align: center;
background: #f5f5f5;
padding-top: 20px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003137}}
#footer ul {
line-height: 24px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003141}}
#footer ul li {
display: inline;
}
/*list*/
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003146}}
#menu ul {
width: 100%;
height: 40px;
text-align: center;
background: #efefef;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003153}}
#menu ul li {
display: inline;
line-height: 40px;
font-size: 16px;
margin: 0 10px 0 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003160}}
.menu_nav img {
position: relative;
vertical-align: bottom;
right: 21px;
visibility: hidden;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003167}}
.menu_active a {
color: #333333;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003171}}
.menu_active img {
visibility: visible;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003175}}
.content_list {
width: 100%;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003179}}
.content_list .list_details {
margin: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003183}}
.dashed {
width: 100%;
height: 1px;
border-bottom: 1px dashed #5d5d5d;
margin-top: 10px;
}
/*detail*/
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003191}}
.details_content_overview {
margin: 10px 0 10px 10px;
line-height: 24px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003196}}
.overview_title {
font-size: 18px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003200}}
.details_content_overview .overview_details span {
margin-right: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003204}}
.user_name {
line-height: 30px;
font-size: 16px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003209}}
.big_v {
margin-left: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003213}}
.support {
font-size: 16px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003217}}
.date {
float: right;
font-size: 12px;
font-weight: 500;
color: #d4d4d4;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003224}}
.margin_bottom {
margin-bottom: 10px;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003228}}
.swipe {
overflow: hidden;
visibility: hidden;
position: relative;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003232}}
.swipe .swipe-wrap {
overflow: hidden;
position: relative;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003235}}
.swipe .swipe-wrap .item {
float: left;
width: 100%;
position: relative;
height: 251px;
text-align: left;
}
@media -sass-debug-info{filename{font-family:file\:\/\/D\:\/Infindo\/Code\/AppXquare\/WebContent\/zzyj\/app\/styles\/style\.scss}line{font-family:\00003241}}
.swipe .swipe-wrap .item span.slider_font {
width: 100%;
height: 50px;
line-height: 50px;
text-align: left;
text-indent: 10px;
position: absolute;
z-index: 10;
bottom: 0;
background: #333333;
opacity: .45;
filter: alpha(opacity=45);
}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/styles/style.css
|
CSS
|
gpl3
| 11,081
|
@charset "utf-8";
@import url("../skin/skin.css");
/* CSS Document */
html, body, h1, h2, h3, h4, h5, h6, p, form, dl, dt, dd, ul, li, ol, img, input, select, div, table, tr, td, thead, tbody, p {
border: 0;
font-family: Arial, sans-serif "微软雅黑";
margin: 0;
padding: 0;
font-size: 12px;
color:#5d5d5d;
word-wrap: break-word;
}
em{ font-style:normal;}
html, body {
height: 100%;
}
ul {
list-style-type: none;
}
a {
text-decoration: none;
color: #0088cc;
}
a:hover, a:focus {
color: #005580;
}
.clearfix:before, .clearfix:after {
content:"";
display:table;
}
.clearfix:after{
clear:both;
}
.clearfix{
*zoom:1;/*ie6,7*/
}
.float_left{ float:left;}
.float_right{ float:right;}
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/styles/global.scss
|
SCSS
|
gpl3
| 755
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="aaron.chen@niuapp.com" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<title>众智云集移动官网</title>
<!-- build:css styles/main.css -->
<link rel="stylesheet" href="styles/global.css">
<link rel="stylesheet" href="styles/style.css">
<!-- endbuild -->
</head>
<body>
<!-- build:js scripts/components.js -->
<script src="bower_components/jquery/jquery.js"></script>
<script src="bower_components/handlebars/handlebars.js"></script>
<script src="bower_components/ember/ember.js"></script>
<script src="bower_components/jquery.validation/jquery.validate.js"></script>
<script src="bower_components/jquery.cookie/jquery.cookie.js"></script>
<script src = "bower_components/Swipe/swipe.js"></script>
<!-- endbuild -->
<!-- build:js(.tmp) scripts/templates.js -->
<script src="../.tmp/scripts/compiled-templates.js"></script>
<!-- endbuild -->
<!-- build:js(.tmp) scripts/main.js -->
<script src="../.tmp/scripts/combined-scripts.js"></script>
<!-- endbuild -->
</body>
</html>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/app/index.html
|
HTML
|
gpl3
| 1,388
|
grunt watch
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/mobi/watch.bat
|
Batchfile
|
gpl3
| 11
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HOMEPAGE</title>
</head>
<body>
HOMEPAGE
</body>
</html>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/index.html
|
HTML
|
gpl3
| 145
|
<%@ page contentType="text/html;charset=UTF-8"%>
<!-- <%@ include file="/common/taglibs.jsp"%> -->
<div>
__INDEX__
</div>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/WEB-INF/jsp/index.jsp
|
Java Server Pages
|
gpl3
| 128
|
<%@ page contentType="text/html;charset=UTF-8"%>
<!-- <%@ include file="/common/taglibs.jsp"%> -->
<script type=text/javascript src="${ctx}/js/home.js"></script>
<div>
__HOME__
</div>
|
zzyj-mobi
|
trunk/ zzyj-mobi --username aaronchen2k@gmail.com/zzyj-mobi/WebContent/WEB-INF/jsp/front/home.jsp
|
Java Server Pages
|
gpl3
| 193
|
//
// AddEmailDBManager.m
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import "AddEmailDBManager.h"
static AddEmailDBManager *sharedSQLiteManager = nil;
#pragma mark Private Method Declarations
@interface AddEmailDBManager (private)
- (NSString *)databaseFilepath;
- (void)executeUpdateSQL:(NSString *) updateSQL;
@end
@implementation AddEmailDBManager
@synthesize databaseFilepath,delegate;
#pragma mark From SyncManager
#pragma mark Add DB management
NSInteger intSortReverse(id num1, id num2, void *context){
int v1 = [num1 intValue];
int v2 = [num2 intValue];
if (v1 < v2)
return NSOrderedDescending;
else if (v1 > v2)
return NSOrderedAscending;
else
return NSOrderedSame;
}
-(NSArray*)emailDBNames {
// returns the names of all email DB's in the directory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex: 0];
NSString* file;
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
NSMutableArray *numbers = [NSMutableArray arrayWithCapacity:20];
while (file = [dirEnum nextObject]) {
if ([[file pathExtension] isEqualToString: @"trie"]) {
NSString* fileName = [file stringByDeletingPathExtension];
if ([[fileName substringToIndex:6] isEqualToString:@"email-"]) {
NSString* fileNumber = [fileName substringFromIndex:6];
int number = [fileNumber intValue];
[numbers addObject:[NSNumber numberWithInt:number]];
}
}
}
// sort the array in reverse (we want the newest db files first)
NSArray* sortedArray = [numbers sortedArrayUsingFunction:intSortReverse context:NULL];
NSMutableArray* res = [NSMutableArray arrayWithCapacity:[sortedArray count]];
for(int i = 0; i < [sortedArray count]; i++) {
int num = [[sortedArray objectAtIndex:i] intValue];
NSString* fileName = [NSString stringWithFormat:@"email-%i.trie", num];
[res addObject:fileName];
}
return res;
}
-(int)highestDBNum {
// returns the highest DB number currently out there ...
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex: 0];
NSString* file;
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
int highest = 0;
while (file = [dirEnum nextObject]) {
if ([[file pathExtension] isEqualToString: @"trie"]) {
NSString* fileName = [file stringByDeletingPathExtension];
if ([[fileName substringToIndex:6] isEqualToString:@"email-"]) {
NSString* fileNumber = [fileName substringFromIndex:6];
int number = [fileNumber intValue];
if(number > highest) {
highest = number;
}
}
}
}
return highest;
}
-(NSString*)addDBFilename {
// what the current add DB is called (note that this goes to disk)
int highest = [self highestDBNum];
return [NSString stringWithFormat:@"email-%i.trie", highest];
}
-(NSString*)nextAddDBFilename {
// what the next add DB should be called (note that this goes to disk)
int highest = [self highestDBNum];
return [NSString stringWithFormat:@"email-%i.trie", highest+1];
}
-(BOOL)shouldRolloverAddEmailDB {
if(emailCountStmt == nil) {
NSString* querySQL = @"SELECT count(datetime) FROM email;";
int dbrc = sqlite3_prepare_v2([[AddEmailDBManager sharedManager] database], [querySQL UTF8String], -1, &emailCountStmt, nil);
if (dbrc != SQLITE_OK) {
assert(NO);//That's a fail fast sort of thing.
}
}
//Exec query
int count = 0;
if(sqlite3_step(emailCountStmt) == SQLITE_ROW) {
count = sqlite3_column_int(emailCountStmt, 0);
}
sqlite3_reset(emailCountStmt);
return (count >= EMAIL_DB_COUNT_LIMIT);
}
-(void)rolloverAddEmailDB {
// rolls over AddEmailDB, starts a new email-X file
[SyncManager clearPreparedStmts];
[[AddEmailDBManager sharedManager] close];
// create new, empty db file
NSString* fileName = [self nextAddDBFilename];
NSString *dbPath = [StringUtil filePathInDocumentsDirectoryForFileName:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:dbPath])
{
[[NSFileManager defaultManager] createFileAtPath:dbPath contents:nil attributes:nil];
}
[[AddEmailDBManager sharedManager] setDatabaseFilepath:[StringUtil filePathInDocumentsDirectoryForFileName:fileName]];
[[AddEmailDBManager sharedManager] setDelegate:self];
[StartupLogic tableCheck];
}
-(unsigned long long)totalFileSize {
NSFileManager *fileManager = [NSFileManager defaultManager];
unsigned long long total = 0;
NSString *dbPath = [StringUtil filePathInDocumentsDirectoryForFileName:CONTACT_DB_NAME];
NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:dbPath traverseLink:YES];
if (fileAttributes != nil) {
NSNumber *fileSize;
if (fileSize = [fileAttributes objectForKey:NSFileSize]) {
total += [fileSize unsignedLongValue];
}
}
NSArray* a = [self emailDBNames];
NSEnumerator* e = [a objectEnumerator];
NSString* fileName;
while(fileName = [e nextObject]) {
NSString *dbPath = [StringUtil filePathInDocumentsDirectoryForFileName:fileName];
NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:dbPath traverseLink:YES];
if (fileAttributes != nil) {
NSNumber *fileSize;
if (fileSize = [fileAttributes objectForKey:NSFileSize]) {
total += [fileSize unsignedLongValue];
}
}
}
return total;
}
#pragma mark -
#pragma mark Singleton Methods
+ (id)sharedManager
{
@synchronized(self)
{
if (sharedSQLiteManager == nil)
sharedSQLiteManager = [[[self alloc] init] retain];;
}
return sharedSQLiteManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedSQLiteManager == nil) {
sharedSQLiteManager = [[super allocWithZone:zone] retain];
}
}
return sharedSQLiteManager;
return nil;
}
//Einar added for sanity.
+ (BOOL)beginTransaction
{
const char *sql1 = "BEGIN TRANSACTION"; //Should be exclusive?
sqlite3_stmt *begin_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql1, -1, &begin_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(begin_statement);
return NO;
}
if (sqlite3_step(begin_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in beginTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(begin_statement);
return NO;
}
sqlite3_finalize(begin_statement);
return YES;
}
+ (BOOL)endTransaction
{
const char *sql2 = "COMMIT TRANSACTION";
sqlite3_stmt *commit_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql2, -1, &commit_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(commit_statement);
return NO;
}
if (sqlite3_step(commit_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in endTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(commit_statement);
return NO;
}
sqlite3_finalize(commit_statement);
return YES;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
// never release
}
- (id)autorelease
{
return self;
}
#pragma mark -
#pragma mark Public Instance Methods
-(sqlite3 *)database {
static BOOL first = YES;
if (first || database == NULL) {
first = NO;
if (!sqlite3_open([[self databaseFilepath] UTF8String], &database) == SQLITE_OK) {
NSAssert1(0, @"Attempted to open database at path %s, but failed",[[self databaseFilepath] UTF8String]);
// Even though the open failed, call close to properly clean up resources.
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
sqlite3_close(database);
} else {
// Modify cache size so we don't overload memory. 50 * 1.5kb
[self executeUpdateSQL:@"PRAGMA CACHE_SIZE=1000"];
// Default to UTF-8 encoding
[self executeUpdateSQL:@"PRAGMA encoding = \"UTF-8\""];
// Turn on full auto-vacuuming to keep the size of the database down
// This setting can be changed per database using the setAutoVacuum instance method
[self executeUpdateSQL:@"PRAGMA auto_vacuum=1"];
}
}
return database;
}
-(void)close {
// close DB
if(database != NULL) {
sqlite3_close(database);
database = NULL;
}
}
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA auto_vacuum=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)setCacheSize:(NSUInteger)pages
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", pages];
[self executeUpdateSQL:updateSQL];
}
- (void)setLockingMode:(SQLITE3LockingMode)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)deleteDatabase
{
NSString* path = [self databaseFilepath];
NSFileManager* fm = [NSFileManager defaultManager];
[fm removeItemAtPath:path error:nil];
database = NULL;
}
- (void)vacuum
{
[self executeUpdateSQL:@"VACUUM"];
}
#pragma mark -
- (void)dealloc
{
[databaseFilepath release];
[super dealloc];
}
#pragma mark -
#pragma mark Private Methods
- (void)executeUpdateSQL:(NSString *) updateSQL
{
char *errorMsg;
if (sqlite3_exec([self database],[updateSQL UTF8String] , NULL, NULL, &errorMsg) != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to execute SQL '%@' with message '%s'.", updateSQL, errorMsg];
NSAssert(0, errorMessage);
sqlite3_free(errorMsg);
}
}
- (NSString *)databaseFilepath {
if (databaseFilepath == nil) {
//assert(FALSE); // You should init CacheManager first, then this won't happen.
NSMutableString *ret = [NSMutableString string];
NSString *appName = [[NSProcessInfo processInfo] processName];
for (int i = 0; i < [appName length]; i++)
{
NSRange range = NSMakeRange(i, 1);
NSString *oneChar = [appName substringWithRange:range];
if (![oneChar isEqualToString:@" "])
[ret appendString:[oneChar lowercaseString]];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
NSString *saveFileName = [NSString stringWithFormat:@"%@.sqlite3", ret];
NSString *filepath = [saveDirectory stringByAppendingPathComponent:saveFileName];
databaseFilepath = [filepath retain];
if (![[NSFileManager defaultManager] fileExistsAtPath:saveDirectory])
[[NSFileManager defaultManager] createDirectoryAtPath:saveDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}
return databaseFilepath;
}
@end
|
zzj9008-aaa
|
DBAccessors/AddEmailDBAccessor.m
|
Objective-C
|
asf20
| 11,592
|
//
// ContactDBManager.h
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#import "AddEmailDBManager.h" // for SQLite3 constants
#import <objc/runtime.h>
#import <objc/message.h>
@interface ContactDBManager : NSObject {
@private
ContactDBManager *singleton;
NSString *databaseFilepath;
sqlite3 *database;
}
@property (readwrite,retain) NSString *databaseFilepath;
@property (readwrite,retain) id delegate;
+ (id)sharedManager;
+ (BOOL)beginTransaction;
+ (BOOL)endTransaction;
- (sqlite3 *)database;
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode;
- (void)setCacheSize:(NSUInteger)pages;
- (void)setLockingMode:(SQLITE3LockingMode)mode;
- (void)deleteDatabase;
- (void)vacuum;
@end
|
zzj9008-aaa
|
DBAccessors/ContactDBAccessor.h
|
Objective-C
|
asf20
| 1,588
|
//
// ContactDBManager.m
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import "UidDBManager.h"
#define UID_DB_NAME @"uid.rdb"
static UidDBManager *sharedSQLiteManager = nil;
#pragma mark Private Method Declarations
@interface UidDBManager (private)
- (NSString *)databaseFilepath;
- (void)executeUpdateSQL:(NSString *) updateSQL;
@end
@implementation UidDBManager
@synthesize databaseFilepath;
#pragma mark -
#pragma mark Singleton Methods
+ (id)sharedManager
{
@synchronized(self)
{
if (sharedSQLiteManager == nil)
sharedSQLiteManager = [[[self alloc] init] retain];;
}
return sharedSQLiteManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedSQLiteManager == nil) {
sharedSQLiteManager = [[super allocWithZone:zone] retain];
}
}
return sharedSQLiteManager;
return nil;
}
//Einar added for sanity.
+ (BOOL)beginTransaction
{
const char *sql1 = "BEGIN TRANSACTION"; //Should be exclusive?
sqlite3_stmt *begin_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql1, -1, &begin_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(begin_statement);
return NO;
}
if (sqlite3_step(begin_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in beginTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(begin_statement);
return NO;
}
sqlite3_finalize(begin_statement);
return YES;
}
+ (BOOL)endTransaction
{
const char *sql2 = "COMMIT TRANSACTION";
sqlite3_stmt *commit_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql2, -1, &commit_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(commit_statement);
return NO;
}
if (sqlite3_step(commit_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in endTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(commit_statement);
return NO;
}
sqlite3_finalize(commit_statement);
return YES;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
// never release
}
- (id)autorelease
{
return self;
}
#pragma mark -
#pragma mark Public Instance Methods
-(sqlite3 *)database
{
static BOOL first = YES;
if (first || database == NULL)
{
first = NO;
if (!sqlite3_open([[self databaseFilepath] UTF8String], &database) == SQLITE_OK)
{
NSAssert1(0, @"Attempted to open database at path %s, but failed",[[self databaseFilepath] UTF8String]);
// Even though the open failed, call close to properly clean up resources.
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
sqlite3_close(database);
}
else
{
// Modify cache size so we don't overload memory. 50 * 1.5kb
[self executeUpdateSQL:@"PRAGMA CACHE_SIZE=500"];
// Default to UTF-8 encoding
[self executeUpdateSQL:@"PRAGMA encoding = \"UTF-8\""];
// Turn on full auto-vacuuming to keep the size of the database down
// This setting can be changed per database using the setAutoVacuum instance method
[self executeUpdateSQL:@"PRAGMA auto_vacuum=1"];
}
}
return database;
}
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA auto_vacuum=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)setCacheSize:(NSUInteger)pages
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", pages];
[self executeUpdateSQL:updateSQL];
}
- (void)setLockingMode:(SQLITE3LockingMode)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)deleteDatabase
{
NSString* path = [self databaseFilepath];
NSFileManager* fm = [NSFileManager defaultManager];
[fm removeItemAtPath:path error:nil];
database = NULL;
}
- (void)vacuum
{
[self executeUpdateSQL:@"VACUUM"];
}
#pragma mark -
- (void)dealloc
{
[databaseFilepath release];
[super dealloc];
}
#pragma mark -
#pragma mark Private Methods
- (void)executeUpdateSQL:(NSString *) updateSQL
{
char *errorMsg;
if (sqlite3_exec([self database],[updateSQL UTF8String] , NULL, NULL, &errorMsg) != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to execute SQL '%@' with message '%s'.", updateSQL, errorMsg];
NSAssert(0, errorMessage);
sqlite3_free(errorMsg);
}
}
- (NSString *)databaseFilepath
{
if (databaseFilepath == nil)
{
//assert(FALSE); // You should init CacheManager first, then this won't happen.
NSMutableString *ret = [NSMutableString string];
NSString *appName = [[NSProcessInfo processInfo] processName];
for (int i = 0; i < [appName length]; i++)
{
NSRange range = NSMakeRange(i, 1);
NSString *oneChar = [appName substringWithRange:range];
if (![oneChar isEqualToString:@" "])
[ret appendString:[oneChar lowercaseString]];
}
//#if (TARGET_OS_COCOTRON)
// NSString *saveDirectory = @"./"; // TODO: default path is undefined on coctron
//#elif (TARGET_OS_MAC && ! TARGET_OS_IPHONE)
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
// NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
// NSString *saveDirectory = [basePath stringByAppendingPathComponent:appName];
//#else
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
//#endif
NSString *saveFileName = [NSString stringWithFormat:@"%@.sqlite3", ret];
NSString *filepath = [saveDirectory stringByAppendingPathComponent:saveFileName];
databaseFilepath = [filepath retain];
if (![[NSFileManager defaultManager] fileExistsAtPath:saveDirectory])
[[NSFileManager defaultManager] createDirectoryAtPath:saveDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}
return databaseFilepath;
}
@end
|
zzj9008-aaa
|
DBAccessors/UidDBAccessor.m
|
Objective-C
|
asf20
| 6,895
|
//
// ContactDBManager.m
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import "ContactDBManager.h"
#define CONTACT_DB_NAME @"contacts.rdb"
static ContactDBManager *sharedSQLiteManager = nil;
#pragma mark Private Method Declarations
@interface ContactDBManager (private)
- (NSString *)databaseFilepath;
- (void)executeUpdateSQL:(NSString *) updateSQL;
@end
@implementation ContactDBManager
@synthesize databaseFilepath;
#pragma mark -
#pragma mark Singleton Methods
+ (id)sharedManager
{
@synchronized(self)
{
if (sharedSQLiteManager == nil)
sharedSQLiteManager = [[[self alloc] init] retain];;
}
return sharedSQLiteManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedSQLiteManager == nil) {
sharedSQLiteManager = [[super allocWithZone:zone] retain];
}
}
return sharedSQLiteManager;
return nil;
}
//Einar added for sanity.
+ (BOOL)beginTransaction
{
const char *sql1 = "BEGIN TRANSACTION"; //Should be exclusive?
sqlite3_stmt *begin_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql1, -1, &begin_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(begin_statement);
return NO;
}
if (sqlite3_step(begin_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in beginTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(begin_statement);
return NO;
}
sqlite3_finalize(begin_statement);
return YES;
}
+ (BOOL)endTransaction
{
const char *sql2 = "COMMIT TRANSACTION";
sqlite3_stmt *commit_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql2, -1, &commit_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(commit_statement);
return NO;
}
if (sqlite3_step(commit_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in endTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(commit_statement);
return NO;
}
sqlite3_finalize(commit_statement);
return YES;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
// never release
}
- (id)autorelease
{
return self;
}
#pragma mark -
#pragma mark Public Instance Methods
-(sqlite3 *)database
{
static BOOL first = YES;
if (first || database == NULL)
{
first = NO;
if (!sqlite3_open([[self databaseFilepath] UTF8String], &database) == SQLITE_OK)
{
NSAssert1(0, @"Attempted to open database at path %s, but failed",[[self databaseFilepath] UTF8String]);
// Even though the open failed, call close to properly clean up resources.
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
sqlite3_close(database);
}
else
{
// Modify cache size so we don't overload memory. 50 * 1.5kb
[self executeUpdateSQL:@"PRAGMA CACHE_SIZE=500"];
// Default to UTF-8 encoding
[self executeUpdateSQL:@"PRAGMA encoding = \"UTF-8\""];
// Turn on full auto-vacuuming to keep the size of the database down
// This setting can be changed per database using the setAutoVacuum instance method
[self executeUpdateSQL:@"PRAGMA auto_vacuum=1"];
}
}
return database;
}
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA auto_vacuum=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)setCacheSize:(NSUInteger)pages
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", pages];
[self executeUpdateSQL:updateSQL];
}
- (void)setLockingMode:(SQLITE3LockingMode)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)deleteDatabase
{
NSString* path = [self databaseFilepath];
NSFileManager* fm = [NSFileManager defaultManager];
[fm removeItemAtPath:path error:nil];
database = NULL;
}
- (void)vacuum
{
[self executeUpdateSQL:@"VACUUM"];
}
#pragma mark -
- (void)dealloc
{
[databaseFilepath release];
[super dealloc];
}
#pragma mark -
#pragma mark Private Methods
- (void)executeUpdateSQL:(NSString *) updateSQL
{
char *errorMsg;
if (sqlite3_exec([self database],[updateSQL UTF8String] , NULL, NULL, &errorMsg) != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to execute SQL '%@' with message '%s'.", updateSQL, errorMsg];
NSAssert(0, errorMessage);
sqlite3_free(errorMsg);
}
}
- (NSString *)databaseFilepath
{
if (databaseFilepath == nil)
{
//assert(FALSE); // You should init CacheManager first, then this won't happen.
NSMutableString *ret = [NSMutableString string];
NSString *appName = [[NSProcessInfo processInfo] processName];
for (int i = 0; i < [appName length]; i++)
{
NSRange range = NSMakeRange(i, 1);
NSString *oneChar = [appName substringWithRange:range];
if (![oneChar isEqualToString:@" "])
[ret appendString:[oneChar lowercaseString]];
}
//#if (TARGET_OS_COCOTRON)
// NSString *saveDirectory = @"./"; // TODO: default path is undefined on coctron
//#elif (TARGET_OS_MAC && ! TARGET_OS_IPHONE)
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
// NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
// NSString *saveDirectory = [basePath stringByAppendingPathComponent:appName];
//#else
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
//#endif
NSString *saveFileName = [NSString stringWithFormat:@"%@.sqlite3", ret];
NSString *filepath = [saveDirectory stringByAppendingPathComponent:saveFileName];
databaseFilepath = [filepath retain];
if (![[NSFileManager defaultManager] fileExistsAtPath:saveDirectory])
[[NSFileManager defaultManager] createDirectoryAtPath:saveDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}
return databaseFilepath;
}
@end
|
zzj9008-aaa
|
DBAccessors/ContactDBAccessor.m
|
Objective-C
|
asf20
| 6,920
|
//
// AddEmailDBManager.m
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import "SearchEmailDBManager.h"
static SearchEmailDBManager *sharedSQLiteManager = nil;
#pragma mark Private Method Declarations
@interface SearchEmailDBManager (private)
- (NSString *)databaseFilepath;
- (void)executeUpdateSQL:(NSString *) updateSQL;
@end
@implementation SearchEmailDBManager
@synthesize databaseFilepath;
#pragma mark -
#pragma mark Singleton Methods
+ (id)sharedManager
{
@synchronized(self)
{
if (sharedSQLiteManager == nil)
sharedSQLiteManager = [[[self alloc] init] retain];;
}
return sharedSQLiteManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedSQLiteManager == nil) {
sharedSQLiteManager = [[super allocWithZone:zone] retain];
}
}
return sharedSQLiteManager;
return nil;
}
//Einar added for sanity.
+ (BOOL)beginTransaction
{
const char *sql1 = "BEGIN TRANSACTION"; //Should be exclusive?
sqlite3_stmt *begin_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql1, -1, &begin_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(begin_statement);
return NO;
}
if (sqlite3_step(begin_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in beginTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(begin_statement);
return NO;
}
sqlite3_finalize(begin_statement);
return YES;
}
+ (BOOL)endTransaction
{
const char *sql2 = "COMMIT TRANSACTION";
sqlite3_stmt *commit_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql2, -1, &commit_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(commit_statement);
return NO;
}
if (sqlite3_step(commit_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in endTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(commit_statement);
return NO;
}
sqlite3_finalize(commit_statement);
return YES;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
// never release
}
- (id)autorelease
{
return self;
}
#pragma mark -
#pragma mark Public Instance Methods
-(sqlite3 *)database {
static BOOL first = YES;
if (first || database == NULL) {
first = NO;
if (!sqlite3_open([[self databaseFilepath] UTF8String], &database) == SQLITE_OK) {
NSAssert1(0, @"Attempted to open database at path %s, but failed",[[self databaseFilepath] UTF8String]);
// Even though the open failed, call close to properly clean up resources.
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
sqlite3_close(database);
} else {
// Modify cache size so we don't overload memory. 50 * 1.5kb
[self executeUpdateSQL:@"PRAGMA CACHE_SIZE=100"];
// Default to UTF-8 encoding
[self executeUpdateSQL:@"PRAGMA encoding = \"UTF-8\""];
}
}
return database;
}
-(void)close {
// close DB
if(database != NULL) {
sqlite3_close(database);
database = NULL;
}
}
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA auto_vacuum=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)setCacheSize:(NSUInteger)pages
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", pages];
[self executeUpdateSQL:updateSQL];
}
- (void)setLockingMode:(SQLITE3LockingMode)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)deleteDatabase
{
NSString* path = [self databaseFilepath];
NSFileManager* fm = [NSFileManager defaultManager];
[fm removeItemAtPath:path error:nil];
database = NULL;
}
- (void)vacuum
{
[self executeUpdateSQL:@"VACUUM"];
}
#pragma mark -
- (void)dealloc
{
[databaseFilepath release];
[super dealloc];
}
#pragma mark -
#pragma mark Private Methods
- (void)executeUpdateSQL:(NSString *) updateSQL
{
char *errorMsg;
if (sqlite3_exec([self database],[updateSQL UTF8String] , NULL, NULL, &errorMsg) != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to execute SQL '%@' with message '%s'.", updateSQL, errorMsg];
NSAssert(0, errorMessage);
sqlite3_free(errorMsg);
}
}
- (NSString *)databaseFilepath {
if (databaseFilepath == nil) {
//assert(FALSE); // You should init CacheManager first, then this won't happen.
NSMutableString *ret = [NSMutableString string];
NSString *appName = [[NSProcessInfo processInfo] processName];
for (int i = 0; i < [appName length]; i++)
{
NSRange range = NSMakeRange(i, 1);
NSString *oneChar = [appName substringWithRange:range];
if (![oneChar isEqualToString:@" "])
[ret appendString:[oneChar lowercaseString]];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
NSString *saveFileName = [NSString stringWithFormat:@"%@.sqlite3", ret];
NSString *filepath = [saveDirectory stringByAppendingPathComponent:saveFileName];
databaseFilepath = [filepath retain];
if (![[NSFileManager defaultManager] fileExistsAtPath:saveDirectory])
[[NSFileManager defaultManager] createDirectoryAtPath:saveDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}
return databaseFilepath;
}
@end
|
zzj9008-aaa
|
DBAccessors/SearchEmailDBAccessor.m
|
Objective-C
|
asf20
| 6,309
|
//
// AddEmailDBManager.h
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#import <objc/runtime.h>
#import <objc/message.h>
#import "AddEmailDBManager.h"
@interface SearchEmailDBManager : NSObject {
@private
AddEmailDBManager *singleton;
NSString *databaseFilepath;
sqlite3 *database;
}
@property (readwrite,retain) NSString *databaseFilepath;
+ (id)sharedManager;
+ (BOOL)beginTransaction;
+ (BOOL)endTransaction;
- (sqlite3 *)database;
- (void)close;
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode;
- (void)setCacheSize:(NSUInteger)pages;
- (void)setLockingMode:(SQLITE3LockingMode)mode;
- (void)deleteDatabase;
- (void)vacuum;
@end
|
zzj9008-aaa
|
DBAccessors/SearchEmailDBAccessor.h
|
Objective-C
|
asf20
| 1,543
|
//
// ContactDBManager.h
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#import "AddEmailDBManager.h" // for SQLite3 constants
#import <objc/runtime.h>
#import <objc/message.h>
@interface UidDBManager : NSObject {
@private
UidDBManager *singleton;
NSString *databaseFilepath;
sqlite3 *database;
}
@property (readwrite,retain) NSString *databaseFilepath;
+ (id)sharedManager;
+ (BOOL)beginTransaction;
+ (BOOL)endTransaction;
- (sqlite3 *)database;
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode;
- (void)setCacheSize:(NSUInteger)pages;
- (void)setLockingMode:(SQLITE3LockingMode)mode;
- (void)deleteDatabase;
- (void)vacuum;
@end
|
zzj9008-aaa
|
DBAccessors/UidDBAccessor.h
|
Objective-C
|
asf20
| 1,538
|
//
// AddEmailDBManager.h
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
//#if (TARGET_OS_MAC && ! (TARGET_OS_EMBEDDED || TARGET_OS_ASPEN || TARGET_OS_IPHONE))
//#import <Foundation/Foundation.h>
//#else
#import <UIKit/UIKit.h>
//#endif
//#import "/usr/include/sqlite3.h"
#import "sqlite3.h"
//#if (! TARGET_OS_IPHONE)
//#import <objc/objc-runtime.h>
//#else
#import <objc/runtime.h>
#import <objc/message.h>
//#endif
typedef enum SQLITE3AutoVacuum
{
kSQLITE3AutoVacuumNoAutoVacuum = 0,
kSQLITE3AutoVacuumFullVacuum,
kSQLITE3AutoVacuumIncrementalVacuum,
} SQLITE3AutoVacuum;
typedef enum SQLITE3LockingMode
{
kSQLITE3LockingModeNormal = 0,
kSQLITE3LockingModeExclusive,
} SQLITE3LockingMode;
@interface AddEmailDBManager : NSObject {
id delegate;//Added by Einar. Need to hook into save function
@private
AddEmailDBManager *singleton;
NSString *databaseFilepath;
sqlite3 *database;
}
@property (readwrite,retain) NSString *databaseFilepath;
@property (readwrite,retain) id delegate;
+ (id)sharedManager;
+ (BOOL)beginTransaction;
+ (BOOL)endTransaction;
- (sqlite3 *)database;
- (void)close;
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode;
- (void)setCacheSize:(NSUInteger)pages;
- (void)setLockingMode:(SQLITE3LockingMode)mode;
- (void)deleteDatabase;
- (void)vacuum;
// managing addDB / searchDB
-(NSArray*)emailDBNames;
-(NSString*)addDBFilename;
-(unsigned long long)totalFileSize;
@end
|
zzj9008-aaa
|
DBAccessors/AddEmailDBAccessor.h
|
Objective-C
|
asf20
| 2,267
|
//
// SearchRunner.h
// ReMailIPhone
//
// Created by Gabor Cselle on 3/29/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Executes searches, notifies UI of results.
#import <Foundation/Foundation.h>
#import "sqlite3.h"
#import "StringUtil.h"
#import "ActivityIndicator.h"
#import "JSON.h"
#import "Email.h"
@interface SearchRunner : NSObject {
NSObject *autocompleteLock; // makes sure only one autocomplete happens at a time
NSOperationQueue *operationQueue;
volatile BOOL cancelled;
}
@property (nonatomic,retain) NSObject *autocompleteLock;
@property (assign) volatile BOOL cancelled; // flag for when we cancel a search op
@property (nonatomic,readwrite,retain) NSOperationQueue *operationQueue;
//Interface
+(id)getSingleton;
+ (void)clearPreparedStmts;
-(void)ftSearch:(NSString*)query withDelegate:(id)delegate withSnippetDelims:(NSArray *)snippetDelims startWithDB:(int)dbIndex;
-(void)allMailWithDelegate:(id)delegate startWithDB:(int)dbIndex;
-(void)senderSearch:(NSString*)addressess withDelegate:(id)delegate startWithDB:(int)dbIndex dbMin:(int)dbMin dbMax:(int)dbMax;
-(void)folderSearch:(int)folderNum withDelegate:(id)delegate startWithDB:(int)dbIndex;
-(void)autocomplete:(NSString *)query withDelegate:(id)autocompleteDelegate;
-(NSDictionary*)findContact:(NSString*)name;
-(void)deleteEmail:(int)pk dbNum:(int)dbNum;
-(Email*)loadEmail:(int)pk dbNum:(int)dbNum;
-(void)cancel;
@end
@protocol SearchManagerDelegate
//Called with a local search result in *absolute* position pos
- (void) deliverSearchResults: (NSArray *)results;
//Called with either YES or NO depending on if there are more results after pos.
- (void) deliverAdditionalResults:(NSNumber *)availableResults;
//Called with the number of the DB we're currently searching through
- (void) deliverProgressUpdate:(NSNumber *)progressNum;
@end
|
zzj9008-aaa
|
Classes/SearchRunner.h
|
Objective-C
|
asf20
| 2,396
|
//
// PushSetupViewController.m
// ReMailIPhone
//
// Created by Gabor Cselle on 10/22/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "PushSetupViewController.h"
#import "AppSettings.h"
#import "ActivityIndicator.h"
#import "StringUtil.h"
#import "ReMailAppDelegate.h"
@implementation PushSetupViewController
@synthesize timePicker;
@synthesize disableButton;
@synthesize okButton;
@synthesize remindDescriptionLabel;
@synthesize remindTitleLabel;
@synthesize activityIndicator;
- (void)dealloc {
[disableButton release];
[okButton release];
[timePicker release];
[remindDescriptionLabel release];
[remindTitleLabel release];
[activityIndicator release];
[super dealloc];
}
- (void)viewDidUnload {
[super viewDidUnload];
self.disableButton = nil;
self.okButton = nil;
self.timePicker = nil;
self.remindDescriptionLabel = nil;
self.remindTitleLabel = nil;
self.activityIndicator = nil;
}
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
-(void)viewDidLoad {
[super viewDidLoad];
if([AppSettings pushDeviceToken] == nil) {
[self.disableButton setHidden:YES];
} else {
[self.disableButton setHidden:NO];
}
if([AppSettings pushDeviceToken] != nil) {
self.remindTitleLabel.text = NSLocalizedString(@"Reminders are set up for:", nil);
self.timePicker.date = [AppSettings pushTime];
} else {
self.remindTitleLabel.text = NSLocalizedString(@"Remind every day at:", nil);
}
self.remindDescriptionLabel.text = NSLocalizedString(@"reMail can remind once a day you to download your newest emails.", nil);
[self.disableButton setTitle:NSLocalizedString(@"Disable", nil) forState:UIControlStateNormal];
[self.disableButton setTitle:NSLocalizedString(@"Disable", nil) forState:UIControlStateHighlighted];
[self.activityIndicator setHidden:YES];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
-(void)didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
[self.okButton setEnabled:YES];
[self.disableButton setEnabled:YES];
[self.activityIndicator setHidden:YES];
UIApplication* uia = [UIApplication sharedApplication];
ReMailAppDelegate* appDelegate = uia.delegate;
appDelegate.pushSetupScreen = nil;
NSString* blah = [NSString stringWithFormat:@"%@", error];
UIAlertView* as = [[UIAlertView alloc] initWithTitle:@"Push registration error" message:blah delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[as show];
[as release];
}
-(void)didRegisterForRemoteNotificationsWithDeviceToken:(NSString*)deviceToken {
// send the deviceToken & settings to our server
UIApplication* uia = [UIApplication sharedApplication];
ReMailAppDelegate* appDelegate = uia.delegate;
appDelegate.pushSetupScreen = nil;
[ActivityIndicator on];
int edition = (int)[AppSettings reMailEdition];
int gmtDifference = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate* date = self.timePicker.date;
NSDateFormatter* dateF = [[NSDateFormatter alloc] init];
[dateF setDateFormat:@"HH"];
NSString* hours = [dateF stringFromDate:date];
[dateF setDateFormat:@"mm"];
NSString* minutes = [dateF stringFromDate:date];
[dateF release];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *encodedPostString = [NSString stringWithFormat:@"umd=%@&token=%@&aid=%@&sv=%@&e=%i&gmtd=%i&m=%@&h=%@", md5([AppSettings udid]), deviceToken, [AppSettings appID], [AppSettings version], edition, gmtDifference, minutes, hours];
NSLog(@"pushSetup: %@", encodedPostString);
NSData *postData = [encodedPostString dataUsingEncoding:NSUTF8StringEncoding];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.remail.com/push/register"]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:postData];
//Do the call
NSHTTPURLResponse *urlResponse;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
[request release];
if(error == nil) {
[AppSettings setPushDeviceToken:deviceToken];
[AppSettings setPushTime:self.timePicker.date];
[self.navigationController popViewControllerAnimated:YES];
} else {
NSString* blah = [NSString stringWithFormat:@"%@", error];
UIAlertView* as = [[UIAlertView alloc] initWithTitle:@"Push call error" message:blah delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[as show];
[as release];
}
[ActivityIndicator off];
}
-(IBAction)disableClicked {
[self.activityIndicator setHidden:NO];
[self.activityIndicator startAnimating];
[self.okButton setEnabled:NO];
[self.disableButton setEnabled:NO];
// tell both our server and the UIApplication that we're done!
UIApplication* uia = [UIApplication sharedApplication];
[uia unregisterForRemoteNotifications];
[ActivityIndicator on];
int edition = (int)[AppSettings reMailEdition];
NSString *encodedPostString = [NSString stringWithFormat:@"umd=%@&udid=%@&token=%@&aid=%@&sv=%@&e=%i", md5([AppSettings udid]), [AppSettings udid], [AppSettings pushDeviceToken], [AppSettings appID], [AppSettings version], edition];
NSLog(@"pushSetup: %@", encodedPostString);
NSData *postData = [encodedPostString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.remail.com/push/unregister"]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:postData];
//Do the call
NSHTTPURLResponse *urlResponse;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
[request release];
[ActivityIndicator off];
[AppSettings setPushDeviceToken:nil];
[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)okClicked {
[self.activityIndicator setHidden:NO];
[self.activityIndicator startAnimating];
[self.okButton setEnabled:NO];
[self.disableButton setEnabled:NO];
UIApplication* uia = [UIApplication sharedApplication];
ReMailAppDelegate* appDelegate = uia.delegate;
appDelegate.pushSetupScreen = self;
[uia registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
@end
|
zzj9008-aaa
|
Classes/PushSetupViewController.m
|
Objective-C
|
asf20
| 7,764
|
//
// FolderListViewController.h
// ReMailIPhone
//
// Created by Gabor Cselle on 9/24/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
@interface FolderListViewController : UITableViewController <MFMailComposeViewControllerDelegate> {
NSArray *accountIndices;
NSDictionary *accountFolders;
NSDictionary *accountFolderNums;
}
-(IBAction)composeClick;
@property (nonatomic,retain) NSArray *accountIndices;
@property (nonatomic,retain) NSDictionary *accountFolders;
@property (nonatomic,retain) NSDictionary *accountFolderNums;
@end
|
zzj9008-aaa
|
Classes/FolderListViewController.h
|
Objective-C
|
asf20
| 1,156
|
/*
Copyright (C) 2007 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
/// Adds JSON generation to NSObject subclasses
@interface NSObject (NSObject_SBJSON)
/**
@brief Returns a string containing the receiver encoded as a JSON fragment.
This method is added as a category on NSObject but is only actually
supported for the following objects:
@li NSDictionary
@li NSArray
@li NSString
@li NSNumber (also used for booleans)
@li NSNull
*/
- (NSString *)JSONFragment;
/**
@brief Returns a string containing the receiver encoded in JSON.
This method is added as a category on NSObject but is only actually
supported for the following objects:
@li NSDictionary
@li NSArray
*/
- (NSString *)JSONRepresentation;
@end
|
zzj9008-aaa
|
Classes/NSObject+SBJSON.h
|
Objective-C
|
asf20
| 2,184
|
//
// ConvoCell.h
// ConversationsPrototype
//
// Created by Gabor Cselle on 1/23/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
#import "Three20/Three20.h"
#import "Three20UI/Headers/UIViewAdditions.h"
@interface MailCell : UITableViewCell {
IBOutlet UILabel* dateLabel;
IBOutlet UIImageView* attachmentIndicator;
TTStyledTextLabel *peopleLabel;
TTStyledTextLabel *subjectLabel;
TTStyledTextLabel *bodyLabel;
}
-(void)setupText;
-(void)setTextWithPeople:(NSString*)people withSubject:(NSString*)subject withBody:(NSString*)body;
@property (nonatomic,retain) UILabel* dateLabel;
@property (nonatomic,retain) UIImageView* attachmentIndicator;
@property (nonatomic,retain) TTStyledTextLabel* bodyLabel;
@property (nonatomic,retain) TTStyledTextLabel* subjectLabel;
@property (nonatomic,retain) TTStyledTextLabel* peopleLabel;
@end
|
zzj9008-aaa
|
Classes/MailCell.h
|
Objective-C
|
asf20
| 1,426
|
//
// StringUtil.h
// NextMailIPhone
//
// Created by Gabor Cselle on 2/3/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Various String-related utility functions
#import <Foundation/Foundation.h>
@interface StringUtil : NSObject {
}
+(NSArray*)split:(NSString*)s;
+(NSArray*)split:(NSString*)s forCharacters:(NSString*)c;
+(NSArray*)split:(NSString*)s atString:(NSString*)y;
+(NSString*)trim:(NSString*)s;
+(NSString*)deleteQuoteNewLines:(NSString*)s;
+(NSString*)deleteNewLines:(NSString*)s;
+(NSArray*)trimAndSplit:(NSString*)s;
+(NSString*)compressWhiteSpace:(NSString*)s;
+(NSString*)extractHostName:(NSString *)h;
+(BOOL)isSmtpEmailAddress:(NSString*)s;
+(BOOL)stringStartsWith:(NSString*)string subString:(NSString*)sub;
+(BOOL)stringContains:(NSString*)string subString:(NSString*)sub;
+ (NSString *) filePathInDocumentsDirectoryForFileName:(NSString *)filename;
+ (id) stripUnicodeEscapesToPureAscii:(id)maybeText;
+ (NSString *) combineSQLTerms:(NSArray *)terms withOperand:(NSString *)op;
+ (NSString *) twoCharIntRep:(int)integer;
+ (NSString *) rmQuotes:(NSString *)orig;
+(NSString *)flattenHtml:(NSString *)html;
+(BOOL)isOnlyWhiteSpace:(NSString*)y;
NSString* md5( NSString *str );
@end
|
zzj9008-aaa
|
Classes/StringUtil.h
|
Objective-C
|
asf20
| 1,775
|
//
// WebViewController.h
// NextMailIPhone
//
// Created by Gabor Cselle on 1/16/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
@interface WebViewController : UIViewController <UIWebViewDelegate> {
IBOutlet UIWebView *webView;
IBOutlet UILabel *loadingLabel;
NSString* serverUrl; // url to load from server
IBOutlet UIActivityIndicatorView* loadingIndicator;
}
-(void)doLoad;
-(void)webViewDidFinishLoad:(UIWebView *)webViewLocal;
@property (nonatomic,retain) UIActivityIndicatorView* loadingIndicator;
@property (nonatomic, retain) UIWebView * webView;
@property (nonatomic, retain) UILabel *loadingLabel;
@property (nonatomic, retain) NSString* serverUrl;
@end
|
zzj9008-aaa
|
Classes/WebViewController.h
|
Objective-C
|
asf20
| 1,261
|
//
// HomeViewController.h
// Displays home screen to user, manages toolbar UI and responds to sync status updates
//
// Created by Gabor Cselle on 1/22/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
#import "Three20/Three20.h"
#import "MailboxViewController.h"
#import "SearchEntryViewController.h"
@interface HomeViewController : UIViewController{
IBOutlet UIButton* clientMessageButton;
NSString* clientMessage;
NSString* errorDetail;
}
-(void)loadIt;
-(IBAction)accountListClick:(id)sender;
-(IBAction)searchClick:(id)sender;
-(IBAction)foldersClick:(id)sender;
-(IBAction)toolbarStatusClicked:(id)sender;
-(IBAction)toolbarRefreshClicked:(id)sender;
-(IBAction)clientMessageClick;
-(IBAction)usageClick:(id)sender;
-(void)didChangeClientMessageTo:(id)object;
@property (nonatomic, retain) UIButton* clientMessageButton;
@property (nonatomic, retain) NSString* clientMessage;
@property (nonatomic, retain) NSString* errorDetail;
@end
|
zzj9008-aaa
|
Classes/HomeViewController.h
|
Objective-C
|
asf20
| 1,536
|
//
// UsageViewController.h
// ReMailIPhone
//
// Created by Gabor Cselle on 10/8/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
@interface UsageViewController : UITableViewController<UIActionSheetDelegate, MFMailComposeViewControllerDelegate> {
IBOutlet UILabel* rankHeader;
IBOutlet UIButton* rank0;
IBOutlet UIButton* rank1;
IBOutlet UIButton* rank2;
IBOutlet UIButton* rank3;
IBOutlet UIButton* rank4;
IBOutlet UILabel* recommendTitle;
IBOutlet UILabel* recommendSubtitle;
IBOutlet UITableView* tableViewCopy;
NSMutableArray* contactData;
int lastRowClicked;
}
@property (nonatomic,retain) UILabel* rankHeader;
@property (nonatomic,retain) UIButton* rank0;
@property (nonatomic,retain) UIButton* rank1;
@property (nonatomic,retain) UIButton* rank2;
@property (nonatomic,retain) UIButton* rank3;
@property (nonatomic,retain) UIButton* rank4;
@property (nonatomic,retain) UILabel* recommendTitle;
@property (nonatomic,retain) UILabel* recommendSubtitle;
@property (nonatomic,retain) NSMutableArray* contactData;
@property (nonatomic,retain) UITableView* tableViewCopy;
@property (assign) int lastRowClicked;
-(IBAction)rankClicked:(UIView*)sender;
@end
|
zzj9008-aaa
|
Classes/UsageViewController.h
|
Objective-C
|
asf20
| 1,798
|
//
// StoreItemViewController.m
// ReMailIPhone
//
// Created by Gabor Cselle on 11/11/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "StoreItemViewController.h"
#import "StoreObserver.h"
#import "AppSettings.h"
#import "UsageViewController.h"
@implementation StoreItemViewController
@synthesize product;
@synthesize productTitleLabel;
@synthesize productDescriptionLabel;
@synthesize productImageView;
@synthesize buyButton;
@synthesize recommendLabel;
@synthesize recommendButton;
@synthesize activityIndicator;
- (void)viewDidUnload {
self.product = nil;
self.productTitleLabel = nil;
self.productDescriptionLabel = nil;
self.productImageView = nil;
self.buyButton = nil;
self.activityIndicator = nil;
}
-(IBAction)purchase {
SKPayment *payment = [SKPayment paymentWithProductIdentifier:self.product.productIdentifier];
[[SKPaymentQueue defaultQueue] addPayment:payment];
[self.buyButton setHidden:YES];
[self.activityIndicator setHidden:NO];
[self.activityIndicator startAnimating];
}
-(IBAction)recommend {
NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"Usage" owner:self options:NULL];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
UsageViewController *uivc = nil;
NSObject* nibItem = nil;
while ( (nibItem = [nibEnumerator nextObject]) != NULL) {
if ( [nibItem isKindOfClass: [UsageViewController class]]) {
uivc = (UsageViewController*) nibItem;
break;
}
}
if(uivc == nil) {
return;
}
uivc.toolbarItems = [self.toolbarItems subarrayWithRange:NSMakeRange(0, 2)];
[self.navigationController pushViewController:uivc animated:YES];
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.activityIndicator setHidden:YES];
StoreObserver* so = [StoreObserver getSingleton];
so.delegate = self;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:self.product.priceLocale];
NSString *formattedString = [numberFormatter stringFromNumber:self.product.price];
[self.buyButton setTitle:formattedString forState:UIControlStateNormal];
[self.buyButton setTitle:formattedString forState:UIControlStateHighlighted];
[self.recommendButton setTitle:NSLocalizedString(@"Recommend", nil) forState:UIControlStateNormal];
[self.recommendButton setTitle:NSLocalizedString(@"Recommend", nil) forState:UIControlStateHighlighted];
self.productTitleLabel.text = self.product.localizedTitle;
self.productDescriptionLabel.text = self.product.localizedDescription;
self.productImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"feature%@.png", self.product.productIdentifier]];
}
-(void)viewWillDisappear:(BOOL)animated {
StoreObserver* so = [StoreObserver getSingleton];
if(so.delegate == self) {
so.delegate = nil;
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[super dealloc];
}
#pragma mark StoreObserver delegate stuff
-(void)showError:(NSError*)error {
[self.buyButton setTitle:[self.buyButton titleForState:UIControlStateHighlighted] forState:UIControlStateNormal];
[self.buyButton setHidden:NO];
[self.activityIndicator setHidden:YES];
[self.activityIndicator stopAnimating];
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:error.localizedDescription
message:error.localizedFailureReason
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alertView show];
}
-(void)cancelled {
// user canceled purchase -> reset buy button title
[self.buyButton setTitle:[self.buyButton titleForState:UIControlStateHighlighted] forState:UIControlStateNormal];
}
-(void)purchased:(NSString*)pid {
if([pid isEqualToString:self.product.productIdentifier]) {
[self.navigationController popViewControllerAnimated:YES];
}
}
@end
|
zzj9008-aaa
|
Classes/StoreItemViewController.m
|
Objective-C
|
asf20
| 4,606
|
/*
File: Reachability.m
Abstract: SystemConfiguration framework wrapper.
Version: 1.5
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#import <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#include <netdb.h>
#import "Reachability.h"
#import <SystemConfiguration/SCNetworkReachability.h>
static NSString *kLinkLocalAddressKey = @"169.254.0.0";
static NSString *kDefaultRouteKey = @"0.0.0.0";
static Reachability *_sharedReachability;
// A class extension that declares internal methods for this class.
@interface Reachability()
- (BOOL)isAdHocWiFiNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags;
- (BOOL)isNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags;
- (BOOL)isReachableWithoutRequiringConnection:(SCNetworkReachabilityFlags)flags;
- (SCNetworkReachabilityRef)reachabilityRefForHostName:(NSString *)hostName;
- (SCNetworkReachabilityRef)reachabilityRefForAddress:(NSString *)address;
- (BOOL)addressFromString:(NSString *)IPAddress address:(struct sockaddr_in *)outAddress;
- (void)stopListeningForReachabilityChanges;
@end
@implementation Reachability
@synthesize networkStatusNotificationsEnabled = _networkStatusNotificationsEnabled;
@synthesize hostName = _hostName;
@synthesize address = _address;
@synthesize reachabilityQueries = _reachabilityQueries;
+ (Reachability *)sharedReachability
{
if (!_sharedReachability) {
_sharedReachability = [[Reachability alloc] init];
// Clients of Reachability will typically call [[Reachability sharedReachability] setHostName:]
// before calling one of the status methods.
_sharedReachability.hostName = nil;
_sharedReachability.address = nil;
_sharedReachability.networkStatusNotificationsEnabled = NO;
_sharedReachability.reachabilityQueries = [[NSMutableDictionary alloc] init];
}
return _sharedReachability;
}
- (void) dealloc
{
[self stopListeningForReachabilityChanges];
[_sharedReachability.reachabilityQueries release];
[_sharedReachability release];
[super dealloc];
}
- (BOOL)isReachableWithoutRequiringConnection:(SCNetworkReachabilityFlags)flags
{
// kSCNetworkReachabilityFlagsReachable indicates that the specified nodename or address can
// be reached using the current network configuration.
BOOL isReachable = flags & kSCNetworkReachabilityFlagsReachable;
// This flag indicates that the specified nodename or address can
// be reached using the current network configuration, but a
// connection must first be established.
//
// If the flag is false, we don't have a connection. But because CFNetwork
// automatically attempts to bring up a WWAN connection, if the WWAN reachability
// flag is present, a connection is not required.
BOOL noConnectionRequired = !(flags & kSCNetworkReachabilityFlagsConnectionRequired);
if ((flags & kSCNetworkReachabilityFlagsIsWWAN)) {
noConnectionRequired = YES;
}
return (isReachable && noConnectionRequired) ? YES : NO;
}
// Returns whether or not the current host name is reachable with the current network configuration.
- (BOOL)isHostReachable:(NSString *)host
{
if (!host || ![host length]) {
return NO;
}
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [host UTF8String]);
BOOL gotFlags = SCNetworkReachabilityGetFlags(reachability, &flags);
CFRelease(reachability);
if (!gotFlags) {
return NO;
}
return [self isReachableWithoutRequiringConnection:flags];
}
// This returns YES if the address 169.254.0.0 is reachable without requiring a connection.
- (BOOL)isAdHocWiFiNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags
{
// Look in the cache of reachability queries for one that matches this query.
ReachabilityQuery *query = [self.reachabilityQueries objectForKey:kLinkLocalAddressKey];
SCNetworkReachabilityRef adHocWiFiNetworkReachability = query.reachabilityRef;
// If a cached reachability query was not found, create one.
if (!adHocWiFiNetworkReachability) {
// Build a sockaddr_in that we can pass to the address reachability query.
struct sockaddr_in sin;
bzero(&sin, sizeof(sin));
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
sin.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
adHocWiFiNetworkReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&sin);
query = [[[ReachabilityQuery alloc] init] autorelease];
query.hostNameOrAddress = kLinkLocalAddressKey;
query.reachabilityRef = adHocWiFiNetworkReachability;
// Add the reachability query to the cache.
[self.reachabilityQueries setObject:query forKey:kLinkLocalAddressKey];
}
// If necessary, register for notifcations for the SCNetworkReachabilityRef on the current run loop.
// If an existing SCNetworkReachabilityRef was found in the cache, we can reuse it and register
// to receive notifications from it in the current run loop, which may be different than the run loop
// that was previously used when registering the SCNetworkReachabilityRef for notifications.
// -scheduleOnRunLoop: will schedule only if network status notifications are enabled in the Reachability instance.
// By default, they are not enabled.
[query scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
SCNetworkReachabilityFlags addressReachabilityFlags;
BOOL gotFlags = SCNetworkReachabilityGetFlags(adHocWiFiNetworkReachability, &addressReachabilityFlags);
if (!gotFlags) {
// There was an error getting the reachability flags.
return NO;
}
// Callers of this method might want to use the reachability flags, so if an 'out' parameter
// was passed in, assign the reachability flags to it.
if (outFlags) {
*outFlags = addressReachabilityFlags;
}
return [self isReachableWithoutRequiringConnection:addressReachabilityFlags];
}
// ReachabilityCallback is registered as the callback for network state changes in startListeningForReachabilityChanges.
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Post a notification to notify the client that the network reachability changed.
[[NSNotificationCenter defaultCenter] postNotificationName:@"kNetworkReachabilityChangedNotification" object:nil];
[pool release];
}
// Perform a reachability query for the address 0.0.0.0. If that address is reachable without
// requiring a connection, a network interface is available. We'll have to do more work to
// determine which network interface is available.
- (BOOL)isNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags
{
ReachabilityQuery *query = [self.reachabilityQueries objectForKey:kDefaultRouteKey];
SCNetworkReachabilityRef defaultRouteReachability = query.reachabilityRef;
// If a cached reachability query was not found, create one.
if (!defaultRouteReachability) {
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
ReachabilityQuery *query = [[[ReachabilityQuery alloc] init] autorelease];
query.hostNameOrAddress = kDefaultRouteKey;
query.reachabilityRef = defaultRouteReachability;
[self.reachabilityQueries setObject:query forKey:kDefaultRouteKey];
}
// If necessary, register for notifcations for the SCNetworkReachabilityRef on the current run loop.
// If an existing SCNetworkReachabilityRef was found in the cache, we can reuse it and register
// to receive notifications from it in the current run loop, which may be different than the run loop
// that was previously used when registering the SCNetworkReachabilityRef for notifications.
// -scheduleOnRunLoop: will schedule only if network status notifications are enabled in the Reachability instance.
// By default, they are not enabled.
[query scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
SCNetworkReachabilityFlags flags;
BOOL gotFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
if (!gotFlags) {
return NO;
}
BOOL isReachable = [self isReachableWithoutRequiringConnection:flags];
// Callers of this method might want to use the reachability flags, so if an 'out' parameter
// was passed in, assign the reachability flags to it.
if (outFlags) {
*outFlags = flags;
}
return isReachable;
}
// Be a good citizen and unregister for network state changes when the application terminates.
- (void)stopListeningForReachabilityChanges
{
// Walk through the cache that holds SCNetworkReachabilityRefs for reachability
// queries to particular hosts or addresses.
NSEnumerator *enumerator = [self.reachabilityQueries objectEnumerator];
ReachabilityQuery *reachabilityQuery;
while (reachabilityQuery = [enumerator nextObject]) {
CFArrayRef runLoops = reachabilityQuery.runLoops;
NSUInteger runLoopCounter, maxRunLoops = CFArrayGetCount(runLoops);
for (runLoopCounter = 0; runLoopCounter < maxRunLoops; runLoopCounter++) {
CFRunLoopRef nextRunLoop = (CFRunLoopRef)CFArrayGetValueAtIndex(runLoops, runLoopCounter);
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityQuery.reachabilityRef, nextRunLoop, kCFRunLoopDefaultMode);
}
CFArrayRemoveAllValues(reachabilityQuery.runLoops);
}
}
/*
Create a SCNetworkReachabilityRef for hostName, which lets us determine if hostName
is currently reachable, and lets us register to receive notifications when the
reachability of hostName changes.
*/
- (SCNetworkReachabilityRef)reachabilityRefForHostName:(NSString *)hostName
{
if (!hostName || ![hostName length]) {
return NULL;
}
// Look in the cache for an existing SCNetworkReachabilityRef for hostName.
ReachabilityQuery *cachedQuery = [self.reachabilityQueries objectForKey:hostName];
SCNetworkReachabilityRef reachabilityRefForHostName = cachedQuery.reachabilityRef;
if (reachabilityRefForHostName) {
return reachabilityRefForHostName;
}
// Didn't find an existing SCNetworkReachabilityRef for hostName, so create one ...
reachabilityRefForHostName = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [hostName UTF8String]);
NSAssert1(reachabilityRefForHostName != NULL, @"Failed to create SCNetworkReachabilityRef for host: %@", hostName);
ReachabilityQuery *query = [[[ReachabilityQuery alloc] init] autorelease];
query.hostNameOrAddress = hostName;
query.reachabilityRef = reachabilityRefForHostName;
// If necessary, register for notifcations for the SCNetworkReachabilityRef on the current run loop.
// If an existing SCNetworkReachabilityRef was found in the cache, we can reuse it and register
// to receive notifications from it in the current run loop, which may be different than the run loop
// that was previously used when registering the SCNetworkReachabilityRef for notifications.
// -scheduleOnRunLoop: will schedule only if network status notifications are enabled in the Reachability instance.
// By default, they are not enabled.
[query scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
// ... and add it to the cache.
[self.reachabilityQueries setObject:query forKey:hostName];
return reachabilityRefForHostName;
}
/*
Create a SCNetworkReachabilityRef for the IP address in addressString, which lets us determine if
the address is currently reachable, and lets us register to receive notifications when the
reachability of the address changes.
*/
- (SCNetworkReachabilityRef)reachabilityRefForAddress:(NSString *)addressString
{
if (!addressString || ![addressString length]) {
return NULL;
}
struct sockaddr_in address;
BOOL gotAddress = [self addressFromString:addressString address:&address];
if (!gotAddress) {
// The attempt to convert addressString to a sockaddr_in failed.
NSAssert1(gotAddress != NO, @"Failed to convert an IP address string to a sockaddr_in: %@", addressString);
return NULL;
}
// Look in the cache for an existing SCNetworkReachabilityRef for addressString.
ReachabilityQuery *cachedQuery = [self.reachabilityQueries objectForKey:addressString];
SCNetworkReachabilityRef reachabilityRefForAddress = cachedQuery.reachabilityRef;
if (reachabilityRefForAddress) {
return reachabilityRefForAddress;
}
// Didn't find an existing SCNetworkReachabilityRef for addressString, so create one.
reachabilityRefForAddress = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (struct sockaddr *)&address);
NSAssert1(reachabilityRefForAddress != NULL, @"Failed to create SCNetworkReachabilityRef for address: %@", addressString);
ReachabilityQuery *query = [[[ReachabilityQuery alloc] init] autorelease];
query.hostNameOrAddress = addressString;
query.reachabilityRef = reachabilityRefForAddress;
// If necessary, register for notifcations for the SCNetworkReachabilityRef on the current run loop.
// If an existing SCNetworkReachabilityRef was found in the cache, we can reuse it and register
// to receive notifications from it in the current run loop, which may be different than the run loop
// that was previously used when registering the SCNetworkReachabilityRef for notifications.
// -scheduleOnRunLoop: will schedule only if network status notifications are enabled in the Reachability instance.
// By default, they are not enabled.
[query scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
// ... and add it to the cache.
[self.reachabilityQueries setObject:query forKey:addressString];
return reachabilityRefForAddress;
}
- (NetworkStatus)remoteHostStatus
{
/*
If the current host name or address is reachable, determine which network interface it is reachable through.
If the host is reachable and the reachability flags include kSCNetworkReachabilityFlagsIsWWAN, it
is reachable through the carrier data network. If the host is reachable and the reachability
flags do not include kSCNetworkReachabilityFlagsIsWWAN, it is reachable through the WiFi network.
*/
SCNetworkReachabilityRef reachabilityRef = nil;
if (self.hostName) {
reachabilityRef = [self reachabilityRefForHostName:self.hostName];
} else if (self.address) {
reachabilityRef = [self reachabilityRefForAddress:self.address];
} else {
NSAssert(self.hostName != nil && self.address != nil, @"No hostName or address specified. Cannot determine reachability.");
return NotReachable;
}
if (!reachabilityRef) {
return NotReachable;
}
SCNetworkReachabilityFlags reachabilityFlags;
BOOL gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &reachabilityFlags);
if (!gotFlags) {
return NotReachable;
}
BOOL reachable = [self isReachableWithoutRequiringConnection:reachabilityFlags];
if (!reachable) {
return NotReachable;
}
if (reachabilityFlags & ReachableViaCarrierDataNetwork) {
return ReachableViaCarrierDataNetwork;
}
return ReachableViaWiFiNetwork;
}
- (NetworkStatus)internetConnectionStatus
{
/*
To determine if the device has an Internet connection, query the address
0.0.0.0. If it's reachable without requiring a connection, first check
for the kSCNetworkReachabilityFlagsIsDirect flag, which tell us if the connection
is to an ad-hoc WiFi network. If it is not, the device can access the Internet.
The next thing to determine is how the device can access the Internet, which
can either be through the carrier data network (EDGE or other service) or through
a WiFi connection.
Note: Knowing that the device has an Internet connection is not the same as
knowing if the device can reach a particular host. To know that, use
-[Reachability remoteHostStatus].
*/
SCNetworkReachabilityFlags defaultRouteFlags;
BOOL defaultRouteIsAvailable = [self isNetworkAvailableFlags:&defaultRouteFlags];
if (defaultRouteIsAvailable) {
if (defaultRouteFlags & kSCNetworkReachabilityFlagsIsDirect) {
// The connection is to an ad-hoc WiFi network, so Internet access is not available.
return NotReachable;
}
else if (defaultRouteFlags & ReachableViaCarrierDataNetwork) {
return ReachableViaCarrierDataNetwork;
}
return ReachableViaWiFiNetwork;
}
return NotReachable;
}
- (NetworkStatus)localWiFiConnectionStatus
{
SCNetworkReachabilityFlags selfAssignedAddressFlags;
/*
To determine if the WiFi connection is to a local ad-hoc network,
check the availability of the address 169.254.x.x. That's an address
in the self-assigned range, and the device will have a self-assigned IP
when it's connected to a ad-hoc WiFi network. So to test if the device
has a self-assigned IP, look for the kSCNetworkReachabilityFlagsIsDirect flag
in the address query. If it's present, we know that the WiFi connection
is to an ad-hoc network.
*/
// This returns YES if the address 169.254.0.0 is reachable without requiring a connection.
BOOL hasLinkLocalNetworkAccess = [self isAdHocWiFiNetworkAvailableFlags:&selfAssignedAddressFlags];
if (hasLinkLocalNetworkAccess && (selfAssignedAddressFlags & kSCNetworkReachabilityFlagsIsDirect)) {
return ReachableViaWiFiNetwork;
}
return NotReachable;
}
// Convert an IP address from an NSString to a sockaddr_in * that can be used to create
// the reachability request.
- (BOOL)addressFromString:(NSString *)IPAddress address:(struct sockaddr_in *)address
{
if (!IPAddress || ![IPAddress length]) {
return NO;
}
memset((char *) address, sizeof(struct sockaddr_in), 0);
address->sin_family = AF_INET;
address->sin_len = sizeof(struct sockaddr_in);
int conversionResult = inet_aton([IPAddress UTF8String], &address->sin_addr);
if (conversionResult == 0) {
NSAssert1(conversionResult != 1, @"Failed to convert the IP address string into a sockaddr_in: %@", IPAddress);
return NO;
}
return YES;
}
@end
@interface ReachabilityQuery ()
- (CFRunLoopRef)startListeningForReachabilityChanges:(SCNetworkReachabilityRef)reachability onRunLoop:(CFRunLoopRef)runLoop;
@end
@implementation ReachabilityQuery
@synthesize reachabilityRef = _reachabilityRef;
@synthesize runLoops = _runLoops;
@synthesize hostNameOrAddress = _hostNameOrAddress;
- (id)init
{
self = [super init];
if (self != nil) {
self.runLoops = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
}
return self;
}
- (void)dealloc
{
CFRelease(self.runLoops);
[super dealloc];
}
- (BOOL)isScheduledOnRunLoop:(CFRunLoopRef)runLoop
{
NSUInteger runLoopCounter, maxRunLoops = CFArrayGetCount(self.runLoops);
for (runLoopCounter = 0; runLoopCounter < maxRunLoops; runLoopCounter++) {
CFRunLoopRef nextRunLoop = (CFRunLoopRef)CFArrayGetValueAtIndex(self.runLoops, runLoopCounter);
if (nextRunLoop == runLoop) {
return YES;
}
}
return NO;
}
- (void)scheduleOnRunLoop:(NSRunLoop *)inRunLoop
{
// Only register for network state changes if the client has specifically enabled them.
if ([[Reachability sharedReachability] networkStatusNotificationsEnabled] == NO) {
return;
}
if (!inRunLoop) {
return;
}
CFRunLoopRef runLoop = [inRunLoop getCFRunLoop];
// Notifications of status changes for each reachability query can be scheduled on multiple run loops.
// To support that, register for notifications for each runLoop.
// -isScheduledOnRunLoop: iterates over all of the run loops that have previously been used
// to register for notifications. If one is found that matches the passed in runLoop argument, there's
// no need to register for notifications again. If one is not found, register for notifications
// using the current runLoop.
if (![self isScheduledOnRunLoop:runLoop]) {
CFRunLoopRef notificationRunLoop = [self startListeningForReachabilityChanges:self.reachabilityRef onRunLoop:runLoop];
if (notificationRunLoop) {
CFArrayAppendValue(self.runLoops, notificationRunLoop);
}
}
}
// Register to receive changes to the 'reachability' query so that we can update the
// user interface when the network state changes.
- (CFRunLoopRef)startListeningForReachabilityChanges:(SCNetworkReachabilityRef)reachability onRunLoop:(CFRunLoopRef)runLoop
{
if (!reachability) {
return NULL;
}
if (!runLoop) {
return NULL;
}
SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
SCNetworkReachabilitySetCallback(reachability, ReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(reachability, runLoop, kCFRunLoopDefaultMode);
return runLoop;
}
@end
|
zzj9008-aaa
|
Classes/Reachability.m
|
Objective-C
|
asf20
| 23,348
|
//
// Email.m
// ReMailIPhone
//
// Created by Gabor Cselle on 1/16/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "Email.h"
#import "LoadEmailDBAccessor.h"
#import "DateUtil.h"
#import "AppSettings.h"
static sqlite3_stmt *inboxStmt = nil;
@implementation Email
@synthesize pk, senderName, senderAddress, tos, ccs, bccs, datetime, msgId, attachments, folder, folderNum, uid, subject, body, metaString;
- (void)dealloc {
[senderName release];
[senderAddress release];
[tos release];
[ccs release];
[bccs release];
[datetime release];
[msgId release];
[attachments release];
[folder release];
[subject release];
[body release];
[metaString release];
[uid release];
if(inboxStmt != nil) {
sqlite3_finalize(inboxStmt);
inboxStmt = nil;
}
[super dealloc];
}
-(BOOL)hasAttachment {
return (self.attachments != nil) && ([self.attachments length] > 2);
}
+(void)createEmailSearchTable {
sqlite3_stmt *testStmt = nil;
// this "prepare statement" part is really just a method for checking if the tables exist yet
NSString *updateStmt = @"SELECT docid FROM search_email WHERE subject = ?;";
int dbrc = sqlite3_prepare_v2([[AddEmailDBAccessor sharedManager] database], [updateStmt UTF8String], -1, &testStmt, nil);
if (dbrc != SQLITE_OK) {
// create index
char* errorMsg;
NSString *statement = @"CREATE VIRTUAL TABLE search_email USING fts3(meta_string, subject, body);";
if([AppSettings dataInitVersion] != nil) { // new search_email format
statement = @"CREATE VIRTUAL TABLE search_email USING fts3(meta, subject, body, sender, tos, ccs, folder);";
}
int res = sqlite3_exec([[AddEmailDBAccessor sharedManager] database],[[NSString stringWithString:statement] UTF8String] , NULL, NULL, &errorMsg);
if (res != SQLITE_OK) {
//NSString *errorMessage = [NSString stringWithFormat:@"Failed to create search_email with message '%s'.", errorMsg];
//NSLog(@"errorMessage = '%@, original ERROR CODE = %i'",errorMessage,res);
}
} else {
sqlite3_finalize(testStmt);
}
}
+(void)tableCheck {
// create tables as appropriate
char* errorMsg;
int res = sqlite3_exec([[AddEmailDBAccessor sharedManager] database],[[NSString stringWithString:@"CREATE TABLE IF NOT EXISTS email "
"(pk INTEGER PRIMARY KEY, datetime REAL, sender_name VARCHAR(50), sender_address VARCHAR(50), "
"tos TEXT, ccs TEXT, bccs TEXT, attachments TEXT, msg_id VARCHAR(50), uid VARCHAR(20), folder VARCHAR(20), folder_num INTEGER, folder_num_1 INTEGER, folder_num_2 INTEGER, folder_num_3 INTEGER, extra INTEGER);"] UTF8String] , NULL, NULL, &errorMsg);
if (res != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to create email table '%s'.", errorMsg];
NSLog(@"errorMessage = '%@, original ERROR CODE = %i'",errorMessage,res);
}
res = sqlite3_exec([[AddEmailDBAccessor sharedManager] database],[[NSString stringWithString:@"CREATE INDEX IF NOT EXISTS email_datetime on email (datetime desc);"] UTF8String] , NULL, NULL, &errorMsg);
if (res != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to create email_datetime table '%s'.", errorMsg];
NSLog(@"errorMessage = '%@, original ERROR CODE = %i'",errorMessage,res);
}
res = sqlite3_exec([[AddEmailDBAccessor sharedManager] database],[[NSString stringWithString:@"CREATE INDEX IF NOT EXISTS email_sender_address on email (sender_address);"] UTF8String] , NULL, NULL, &errorMsg);
if (res != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to create email_sender_address index '%s'.", errorMsg];
NSLog(@"errorMessage = '%@, original ERROR CODE = %i'",errorMessage,res);
}
res = sqlite3_exec([[AddEmailDBAccessor sharedManager] database],[[NSString stringWithString:@"CREATE INDEX IF NOT EXISTS email_folder_num_0 on email (folder_num);"] UTF8String] , NULL, NULL, &errorMsg);
if (res != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to create folder_num_0 index '%s'.", errorMsg];
NSLog(@"errorMessage = '%@, original ERROR CODE = %i'",errorMessage,res);
}
sqlite3_exec([[AddEmailDBAccessor sharedManager] database],[[NSString stringWithString:@"CREATE INDEX IF NOT EXISTS email_folder_num_1 on email (folder_num_1);"] UTF8String] , NULL, NULL, &errorMsg);
sqlite3_exec([[AddEmailDBAccessor sharedManager] database],[[NSString stringWithString:@"CREATE INDEX IF NOT EXISTS email_folder_num_2 on email (folder_num_2);"] UTF8String] , NULL, NULL, &errorMsg);
sqlite3_exec([[AddEmailDBAccessor sharedManager] database],[[NSString stringWithString:@"CREATE INDEX IF NOT EXISTS email_folder_num_3 on email (folder_num_3);"] UTF8String] , NULL, NULL, &errorMsg);
[Email createEmailSearchTable];
}
+(void)deleteWithPk:(int)pk {
char* errorMsg;
int res = sqlite3_exec([[LoadEmailDBAccessor sharedManager] database],[[NSString stringWithFormat:@"DELETE FROM email WHERE pk=%i; DELETE FROM search_email WHERE docid=%i;", pk, pk] UTF8String] , NULL, NULL, &errorMsg);
if (res != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to delete email with message '%s'.", errorMsg];
NSLog(@"errorMessage = '%@, original ERROR CODE = %i'",errorMessage,res);
}
}
-(void)loadData:(int)pkToLoad{
static sqlite3_stmt *emailLoadStmt = nil;
NSString *statement = [NSString stringWithFormat:@"SELECT email.pk, email.datetime, email.sender_name, email.sender_address, email.tos, email.ccs, email.bccs, email.attachments, email.msg_id, email.folder, email.folder_num, email.uid, "
"search_email.meta, search_email.subject, search_email.body FROM email, search_email WHERE email.pk = search_email.docid AND email.pk = %i LIMIT 1;", pkToLoad];
if([AppSettings dataInitVersion] == nil) { // meta used to be called meta_string
statement = [NSString stringWithFormat:@"SELECT email.pk, email.datetime, email.sender_name, email.sender_address, email.tos, email.ccs, email.bccs, email.attachments, email.msg_id, email.folder, email.folder_num, email.uid, "
"search_email.meta_string, search_email.subject, search_email.body FROM email, search_email WHERE email.pk = search_email.docid AND email.pk = %i LIMIT 1;", pkToLoad];
}
int dbrc;
dbrc = sqlite3_prepare_v2([[LoadEmailDBAccessor sharedManager] database], [statement UTF8String], -1, &emailLoadStmt, nil);
if (dbrc != SQLITE_OK) {
NSLog(@"Failed step in loadData with error %s", sqlite3_errmsg([[LoadEmailDBAccessor sharedManager] database]));
}
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss.SSSS"];
//Exec query -
if(sqlite3_step (emailLoadStmt) == SQLITE_ROW) {
self.pk = sqlite3_column_int(emailLoadStmt, 0);
NSDate *date = [NSDate date]; // default == now!
const char * sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 1);
if(sqlVal != nil) {
NSString *dateString = [NSString stringWithUTF8String:sqlVal];
date = [DateUtil datetimeInLocal:[dateFormatter dateFromString:dateString]];
}
self.datetime = date;
NSString* temp = @"";
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 2);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.senderName = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 3);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.senderAddress = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 4);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.tos = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 5);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.ccs = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 6);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.bccs = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 7);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.attachments = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 8);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.msgId = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 9);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.folder = temp;
self.folderNum = sqlite3_column_int(emailLoadStmt, 10);
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 11);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.uid = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 12);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.metaString = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 13);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.subject = temp;
sqlVal = (const char *)sqlite3_column_text(emailLoadStmt, 14);
if(sqlVal != nil) { temp = [NSString stringWithUTF8String:sqlVal]; }
self.body = temp;
}
sqlite3_finalize(emailLoadStmt);
[dateFormatter release];
}
@end
|
zzj9008-aaa
|
Classes/Email.m
|
Objective-C
|
asf20
| 9,721
|
//
// SearchEntryViewController.m
// InboxSearch
//
// Created by Gabor Cselle on 1/13/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "SearchEntryViewController.h"
#import "SearchResultsViewController.h"
#import "PastQuery.h"
#import "BuchheitTimer.h"
#import "SyncManager.h"
#import "DateUtil.h"
#import "AppSettings.h"
#import "AutocompleteCell.h"
@implementation SearchEntryViewController
@synthesize autocompleting;
@synthesize autocompletions;
@synthesize queryHistory;
@synthesize dates;
@synthesize types;
@synthesize lastSearchString;
BOOL autoCompleteMode;
- (void)dealloc {
[autocompletions release];
[queryHistory release];
[dates release];
[lastSearchString release];
[super dealloc];
}
- (void)viewDidUnload {
[super viewDidUnload];
self.autocompletions = nil;
self.queryHistory = nil;
self.dates = nil;
self.lastSearchString = nil;
}
-(void)reloadQueries {
//TODO(einar): Is this autoreleased?
NSDictionary* pastQueries = [PastQuery recentQueries];
self.queryHistory = [pastQueries objectForKey:@"queries"];
self.dates = [pastQueries objectForKey:@"datetimes"];
self.types = [pastQueries objectForKey:@"searchTypes"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
/* // Not showing dates / times anymore
DateUtil* du = [DateUtil getSingleton];
for(int i = 0; i < [self.dates count]; i++) {
NSString* d = [du humanDate:[self.dates objectAtIndex:i]];
[self.dates replaceObjectAtIndex:i withObject:d];
}*/
[dateFormatter release];
}
-(SearchResultsViewController*)createSearchResultsVC {
NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"SearchResults" owner:self options:NULL];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
SearchResultsViewController *res = nil;
NSObject* nibItem = NULL;
while ( (nibItem = [nibEnumerator nextObject]) != NULL) {
if ( [nibItem isKindOfClass: [SearchResultsViewController class]]) {
res = (SearchResultsViewController*) nibItem;
break;
}
}
res.toolbarItems = self.toolbarItems;
return res;
}
-(void)goFTSearch:(NSString*)queryText {
[AppSettings incrementSearchCount];
SearchResultsViewController* res = [self createSearchResultsVC];
res.query = queryText;
res.toolbarItems = self.toolbarItems;
res.isSenderSearch = NO;
[PastQuery recordQuery:queryText withType:0];
// start the search
[res doLoad];
[self.navigationController pushViewController:res animated:YES];
}
-(void)goSenderSearch:(NSString*)senderName withParams:(NSDictionary*)params {
[AppSettings incrementSearchCount];
SearchResultsViewController* res = [self createSearchResultsVC];
res.query = senderName;
res.senderSearchParams = params;
res.isSenderSearch = YES;
[PastQuery recordQuery:senderName withType:1]; //TODO(gabor): need to record that this is a sender search
// start the search
[res doLoad];
[self.navigationController pushViewController:res animated:YES];
}
-(void)goSenderSearch:(NSString*)senderName {
NSDictionary* res = [[SearchRunner getSingleton] findContact:senderName];
if (res == nil) {
return; // some error?
} else {
[self goSenderSearch:senderName withParams:res];
}
}
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
NSLog(@"searchDisplayControllerWillBeginSearch: %@", controller.searchBar.text);
autoCompleteMode = YES;
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller {
NSLog(@"searchDisplayControllerDidEndSearch");
autoCompleteMode = NO;
[self.tableView reloadData];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
SearchRunner *sem = [SearchRunner getSingleton];
[sem cancel];
[self reloadQueries];
[self.tableView reloadData];
[AppSettings setLastpos:@"search"];
}
-(void)viewDidLoad {
self.searchDisplayController.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
self.searchDisplayController.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
self.title = NSLocalizedString(@"reMail Search", @"title");
}
-(void)doLoad {
self.queryHistory = [NSArray array];
self.dates = [NSArray array];
self.types = [NSArray array];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(autoCompleteMode) {
// Apple bug: when returning from SearchResults, the tableView is set wrong.
// That's why we use the autoCompleteMode flag, set in searchDisplayControllerWillBeginSearch
return NSLocalizedString(@"Autocompletions", nil);
} else if(tableView == self.tableView) {
return NSLocalizedString(@"Search History", nil);
} else {
return NSLocalizedString(@"Autocompletions", nil);
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.tableView == tableView) {
return [self.queryHistory count];
} else {
if([self.autocompletions count] > 0) {
return [self.autocompletions count];
} else {
return 1;
}
}
}
/*
-(UITableViewCell*)createNewAutocompleteCell {
UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"AutocompleteCell"];
cell.imageView.image = [UIImage imageNamed:@"convoPerson2.png"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12.0f];
return cell;
}*/
-(AutocompleteCell*)createNewAutocompleteCell {
NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"AutocompleteCell" owner:self options:nil];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
AutocompleteCell* cell = nil;
NSObject* nibItem = nil;
while ((nibItem = [nibEnumerator nextObject]) != nil) {
if([nibItem isKindOfClass: [AutocompleteCell class]]) {
cell = (AutocompleteCell*)nibItem;
[cell setupText];
break;
}
}
return cell;
}
-(UITableViewCell*) createNewSearchHistoryCell {
UITableViewCell* cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SearchPersonHistoryCell"] autorelease];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12.0f];
return cell;
}
-(NSString*)markup:(NSString*)name query:(NSString*)searchString {
searchString = [searchString stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
searchString = [searchString stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
searchString = [searchString stringByReplacingOccurrencesOfString:@">" withString:@">"];
NSRange r = [name rangeOfString:searchString options:NSCaseInsensitiveSearch];
if(r.location == NSNotFound) {
return name;
}
name = [name stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
name = [name stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
name = [name stringByReplacingOccurrencesOfString:@">" withString:@">"];
NSMutableString* s = [NSMutableString stringWithString:name];
[s insertString:@"</span>" atIndex:r.location+r.length];
[s insertString:@"<span class=\"redBox\">" atIndex:r.location];
return s;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.tableView == tableView) {
// search history mode
UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"SearchHistoryCell"];
if (cell == nil) {
cell = [self createNewSearchHistoryCell];
}
if([self.queryHistory count] <= indexPath.row || [self.dates count] <= indexPath.row) {
// overflow
cell.textLabel.text = @"";
cell.textLabel.textColor = [UIColor blackColor];
cell.detailTextLabel.text = @"";
return cell;
}
cell.textLabel.text = (NSString*)[self.queryHistory objectAtIndex:indexPath.row];
cell.detailTextLabel.text = (NSString*)[self.dates objectAtIndex:indexPath.row];
if([[self.types objectAtIndex:indexPath.row] intValue] == 0) {
cell.imageView.image = [UIImage imageNamed:@"textSearch.png"];
} else {
cell.imageView.image = [UIImage imageNamed:@"convoPerson2.png"];
}
return cell;
} else {
if([self.autocompletions count] == 0) {
// "No autocompletions" cell
UITableViewCell* cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"SearchHistoryCell"];
if (cell == nil) {
cell = [self createNewSearchHistoryCell];
}
if(!self.autocompleting || ([self.lastSearchString length] > 0 && [self.autocompletions count] == 0)) {
cell.textLabel.text = NSLocalizedString(@"No autocompletions", nil);
} else {
cell.textLabel.text = NSLocalizedString(@"Autocompleting ...", nil);
}
cell.textLabel.textColor = [UIColor darkGrayColor];
return cell;
}
// autocomplete mode
AutocompleteCell* acell = (AutocompleteCell*)[tableView dequeueReusableCellWithIdentifier:@"AutocompleteCell"];
if (acell == nil) {
acell = [self createNewAutocompleteCell];
}
NSDictionary* autocompletion = nil;
@synchronized(self) {
if(indexPath.row < [self.autocompletions count]) {
autocompletion = [self.autocompletions objectAtIndex:indexPath.row];
// this makes sure the autocompletion+contents don't get garbage-collected as we're displaying it.
[autocompletion retain];
}
}
if(autocompletion == nil) {
// overflow
acell.imageView.image = nil;
acell.detailTextLabel.text = @"";
[acell setName:@"" withAddresses:@""];
return acell;
}
acell.imageView.image = [UIImage imageNamed:@"convoPerson3.png"];
NSString* name = [autocompletion objectForKey:@"name"];
name = [self markup:name query:self.lastSearchString];
// need to get rid of the "'"s before displaying text to the user
NSString* addresses = [[autocompletion objectForKey:@"emailAddresses"] stringByReplacingOccurrencesOfString:@"'" withString:@""];
[acell setName:name withAddresses:addresses];
[autocompletion release];
return acell;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.searchDisplayController.searchBar resignFirstResponder];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if(self.tableView == tableView) {
NSString *queryText = [self.queryHistory objectAtIndex:indexPath.row];
if([[self.types objectAtIndex:indexPath.row] intValue] == 1) {
// sender search
[self goSenderSearch:queryText];
} else {
// full-text search
[self goFTSearch:queryText];
}
} else {
if(indexPath.row >= [self.autocompletions count]) {
return;
}
NSDictionary* autocompletion = [self.autocompletions objectAtIndex:indexPath.row];
NSString* senderName = [autocompletion objectForKey:@"name"];
[self goSenderSearch:senderName withParams:autocompletion];
}
}
-(void)runAutocomplete {
NSString* currentString = self.searchDisplayController.searchBar.text;
if (self.lastSearchString == nil) {
self.lastSearchString = @"";
}
if ([currentString isEqualToString:self.lastSearchString]) {
return;
}
if([self.lastSearchString length] > 0 && [StringUtil stringStartsWith:currentString subString:self.lastSearchString] && [self.autocompletions count] == 0) {
// don't search if there were no autocompletions last time either
self.autocompleting = NO;
return;
}
self.lastSearchString = [currentString copy];
[self.lastSearchString release];
NSString* autocompleteSearchString = [NSString stringWithFormat:@"%@*", currentString];
//Invoke query parser and auto complete
SearchRunner* searchManager = [SearchRunner getSingleton];
[searchManager autocomplete:autocompleteSearchString withDelegate:self];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
self.autocompleting = YES;
NSTimer* timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(runAutocomplete) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
- (void)deliverAutocompleteResult:(NSDictionary *)result {
@synchronized(self) {
self.autocompletions = (NSArray*)result;
}
self.autocompleting = NO;
[self.searchDisplayController.searchResultsTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBarLocal{
[searchBarLocal resignFirstResponder];
NSString* queryString = searchBarLocal.text;
[self goFTSearch:queryString];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
NSLog(@"SearchEntryViewController received memory warning");
}
#pragma mark Rotation
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
@end
|
zzj9008-aaa
|
Classes/SearchEntryViewController.m
|
Objective-C
|
asf20
| 13,759
|
//
// StoreItemCell.m
// ReMailIPhone
//
// Created by Gabor Cselle on 11/12/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "StoreItemCell.h"
@implementation StoreItemCell
@synthesize titleLabel;
@synthesize priceLabel;
@synthesize productIcon;
@synthesize purchasedIcon;
- (void)dealloc {
[titleLabel release];
[priceLabel release];
[productIcon release];
[purchasedIcon release];
[super dealloc];
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
|
zzj9008-aaa
|
Classes/StoreItemCell.m
|
Objective-C
|
asf20
| 1,388
|
//
// MailboxViewController.h
// NextMailIPhone
//
// Created by Gabor Cselle on 1/13/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#import "SearchRunner.h"
@interface MailboxViewController : UITableViewController <MFMailComposeViewControllerDelegate, SearchManagerDelegate> {
NSMutableArray *emailData;
int nResults;
int folderNum;
}
-(IBAction)composeClick;
-(void)runLoadDataWithDBNum:(int)dbNum;
-(void)doLoad;
@property (nonatomic, retain) NSMutableArray *emailData;
@property (assign) int nResults;
@property (assign) int folderNum;
@end
|
zzj9008-aaa
|
Classes/MailboxViewController.h
|
Objective-C
|
asf20
| 1,172
|
//
// SearchEntryViewController.h
// NextMailIPhone
//
// Created by Gabor Cselle on 1/13/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
@interface SearchEntryViewController : UITableViewController <UISearchBarDelegate, UISearchDisplayDelegate> {
BOOL autocompleting; // this is YES if autocompleting is currently running ...
NSArray *autocompletions;
NSArray *queryHistory;
NSMutableArray *dates;
NSArray *types;
NSString* lastSearchString;
}
-(void)goFTSearch:(NSString*)queryText;
-(void)goSenderSearch:(NSString*)senderName withParams:(NSDictionary*)params;
-(void)doLoad;
@property (assign) BOOL autocompleting;
@property (nonatomic, retain) NSArray *autocompletions;
@property (nonatomic, retain) NSArray *queryHistory;
@property (nonatomic, retain) NSMutableArray *dates;
@property (nonatomic, retain) NSArray *types;
@property (nonatomic, retain) NSString* lastSearchString;
@end
|
zzj9008-aaa
|
Classes/SearchEntryViewController.h
|
Objective-C
|
asf20
| 1,486
|
//
// WebViewController.m
// NextMailIPhone
//
// Created by Gabor Cselle on 1/16/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "WebViewController.h"
#import "AppSettings.h"
#import "StringUtil.h"
#import "Reachability.h"
@implementation WebViewController
@synthesize webView;
@synthesize loadingLabel;
@synthesize serverUrl;
@synthesize loadingIndicator;
- (void)dealloc {
[loadingLabel release];
[loadingIndicator release];
[webView release];
[serverUrl release];
[super dealloc];
}
- (void)viewDidUnload {
[super viewDidUnload];
self.loadingLabel = nil;
self.loadingIndicator = nil;
self.webView = nil;
self.serverUrl = nil;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if(![StringUtil stringContains:[NSString stringWithFormat:@"%@", error] subString:@"999"]) {
self.loadingLabel.text = NSLocalizedString(@"Error loading webpage.", nil);
}
[self.loadingIndicator stopAnimating];
[self.loadingIndicator setHidden:YES];
}
-(void)webViewDidFinishLoad:(UIWebView *)webViewLocal {
[loadingLabel setHidden:YES];
[loadingIndicator setHidden:YES];
[loadingIndicator stopAnimating];
NSLog(@"WebViewDidFinishLoad %@", webViewLocal.request);
}
-(void)webViewDidStartLoad:(UIWebView *)webViewLocal {
NSLog(@"WebViewDidStartLoad");
}
-(void)viewWillAppear:(BOOL)animated {
[self doLoad];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)doLoad {
self.loadingLabel.text = NSLocalizedString(@"Loading ...", nil);
[loadingLabel setHidden:NO];
[loadingIndicator setHidden:NO];
[loadingIndicator startAnimating];
self.webView.delegate = self;
NSLog(@"Start Loading WebView: %@", self.serverUrl);
NSURL *url = [[NSURL alloc] initWithString:self.serverUrl];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[self.webView loadRequest:request];
[url release];
[request release];
NSLog(@"End loading WebView");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
NSLog(@"WebViewController received memory warning");
}
@end
|
zzj9008-aaa
|
Classes/WebViewController.m
|
Objective-C
|
asf20
| 2,764
|
//
// AddEmailDBAccessor.m
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import "AddEmailDBAccessor.h"
static AddEmailDBAccessor *sharedSQLiteManager = nil;
#pragma mark Private Method Declarations
@interface AddEmailDBAccessor (private)
- (NSString *)databaseFilepath;
- (void)executeUpdateSQL:(NSString *) updateSQL;
@end
@implementation AddEmailDBAccessor
@synthesize databaseFilepath,delegate;
#pragma mark -
#pragma mark Singleton Methods
+ (id)sharedManager
{
@synchronized(self)
{
if (sharedSQLiteManager == nil)
sharedSQLiteManager = [[[self alloc] init] retain];;
}
return sharedSQLiteManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedSQLiteManager == nil) {
sharedSQLiteManager = [[super allocWithZone:zone] retain];
}
}
return sharedSQLiteManager;
return nil;
}
//Einar added for sanity.
+ (BOOL)beginTransaction
{
const char *sql1 = "BEGIN TRANSACTION"; //Should be exclusive?
sqlite3_stmt *begin_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql1, -1, &begin_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(begin_statement);
return NO;
}
if (sqlite3_step(begin_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in beginTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(begin_statement);
return NO;
}
sqlite3_finalize(begin_statement);
return YES;
}
+ (BOOL)endTransaction
{
const char *sql2 = "COMMIT TRANSACTION";
sqlite3_stmt *commit_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql2, -1, &commit_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(commit_statement);
return NO;
}
if (sqlite3_step(commit_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in endTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(commit_statement);
return NO;
}
sqlite3_finalize(commit_statement);
return YES;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
// never release
}
- (id)autorelease
{
return self;
}
#pragma mark -
#pragma mark Public Instance Methods
-(sqlite3 *)database {
static BOOL first = YES;
if (first || database == NULL) {
first = NO;
if (!sqlite3_open([[self databaseFilepath] UTF8String], &database) == SQLITE_OK) {
NSAssert1(0, @"Attempted to open database at path %s, but failed",[[self databaseFilepath] UTF8String]);
// Even though the open failed, call close to properly clean up resources.
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
sqlite3_close(database);
} else {
// Modify cache size so we don't overload memory. 50 * 1.5kb
[self executeUpdateSQL:@"PRAGMA CACHE_SIZE=1000"];
// Default to UTF-8 encoding
[self executeUpdateSQL:@"PRAGMA encoding = \"UTF-8\""];
// Turn on full auto-vacuuming to keep the size of the database down
// This setting can be changed per database using the setAutoVacuum instance method
[self executeUpdateSQL:@"PRAGMA auto_vacuum=1"];
// Turn off synchronous update. This is recommended here:
// http://www.sqlite.org/cvstrac/wiki?p=FtsOne
[self executeUpdateSQL:@"PRAGMA synchronous=NORMAL"];
}
}
return database;
}
-(void)close {
// close DB
if(database != NULL) {
sqlite3_close(database);
database = NULL;
}
}
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA auto_vacuum=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)setCacheSize:(NSUInteger)pages
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", pages];
[self executeUpdateSQL:updateSQL];
}
- (void)setLockingMode:(SQLITE3LockingMode)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)deleteDatabase
{
NSString* path = [self databaseFilepath];
NSFileManager* fm = [NSFileManager defaultManager];
[fm removeItemAtPath:path error:nil];
database = NULL;
}
- (void)vacuum
{
[self executeUpdateSQL:@"VACUUM"];
}
#pragma mark -
- (void)dealloc
{
[databaseFilepath release];
[super dealloc];
}
#pragma mark -
#pragma mark Private Methods
- (void)executeUpdateSQL:(NSString *) updateSQL
{
char *errorMsg;
if (sqlite3_exec([self database],[updateSQL UTF8String] , NULL, NULL, &errorMsg) != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to execute SQL '%@' with message '%s'.", updateSQL, errorMsg];
NSAssert(0, errorMessage);
sqlite3_free(errorMsg);
}
}
- (NSString *)databaseFilepath {
if (databaseFilepath == nil) {
//assert(FALSE); // You should init CacheManager first, then this won't happen.
NSMutableString *ret = [NSMutableString string];
NSString *appName = [[NSProcessInfo processInfo] processName];
for (int i = 0; i < [appName length]; i++)
{
NSRange range = NSMakeRange(i, 1);
NSString *oneChar = [appName substringWithRange:range];
if (![oneChar isEqualToString:@" "])
[ret appendString:[oneChar lowercaseString]];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
NSString *saveFileName = [NSString stringWithFormat:@"%@.sqlite3", ret];
NSString *filepath = [saveDirectory stringByAppendingPathComponent:saveFileName];
databaseFilepath = [filepath retain];
if (![[NSFileManager defaultManager] fileExistsAtPath:saveDirectory])
[[NSFileManager defaultManager] createDirectoryAtPath:saveDirectory withIntermediateDirectories:YES attributes:nil error:nil];
}
return databaseFilepath;
}
@end
|
zzj9008-aaa
|
Classes/AddEmailDBAccessor.m
|
Objective-C
|
asf20
| 6,697
|
//
// UpsellViewController.m
// ReMailIPhone
//
// Created by Gabor Cselle on 10/11/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "UpsellViewController.h"
#import "UsageViewController.h"
@implementation UpsellViewController
@synthesize featureFreeLabel;
@synthesize descriptionLabel;
@synthesize howToActivateLabel;
@synthesize recommendationsToMake;
@synthesize recommendButton;
- (void)dealloc {
[super dealloc];
}
-(void)viewDidUnload {
[super viewDidUnload];
self.featureFreeLabel = nil;
self.descriptionLabel = nil;
self.howToActivateLabel = nil;
self.featureFreeLabel = nil;
self.recommendButton = nil;
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.recommendButton setTitle:NSLocalizedString(@"Recommend reMail", nil) forState:UIControlStateNormal];
[self.recommendButton setTitle:NSLocalizedString(@"Recommend reMail", nil) forState:UIControlStateSelected];
[self.recommendButton setTitle:NSLocalizedString(@"Recommend reMail", nil) forState:UIControlStateHighlighted];
self.descriptionLabel.text = NSLocalizedString(@"This feature lets you connect multiple Gmail accounts to reMail", nil);
self.howToActivateLabel.text = NSLocalizedString(@"How to Activate", nil);
self.featureFreeLabel.text = [NSString stringWithFormat:NSLocalizedString(@"You can activate this functionality by recommending reMail to %i of your friends.", nil),
self.recommendationsToMake];
}
-(IBAction)recommendRemail {
NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"Usage" owner:self options:NULL];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
UsageViewController *uivc = nil;
NSObject* nibItem = NULL;
while ( (nibItem = [nibEnumerator nextObject]) != NULL) {
if ( [nibItem isKindOfClass: [UsageViewController class]]) {
uivc = (UsageViewController*) nibItem;
break;
}
}
if(uivc == nil) {
return;
}
uivc.toolbarItems = [self.toolbarItems subarrayWithRange:NSMakeRange(0, 2)];
[self.navigationController pushViewController:uivc animated:YES];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
@end
|
zzj9008-aaa
|
Classes/UpsellViewController.m
|
Objective-C
|
asf20
| 2,918
|
//
// PastQuery.h
// ReMailIPhone
//
// Created by Gabor Cselle on 1/18/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Represents a query that the user has run in the past.
#import <Foundation/Foundation.h>
@interface PastQuery : NSObject {
NSDate *datetime;
NSString *text;
}
+(void)clearAll;
+(void)tableCheck;
+(NSDictionary*)recentQueries;
+(void)recordQuery:(NSString*)queryText withType:(int)type;
@property (nonatomic,readwrite,retain) NSDate *datetime;
@property (nonatomic,readwrite,retain) NSString *text;
@end
|
zzj9008-aaa
|
Classes/PastQuery.h
|
Objective-C
|
asf20
| 1,096
|
/*
Copyright (C) 2007 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "NSObject+SBJSON.h"
#import "SBJSON.h"
@implementation NSObject (NSObject_SBJSON)
- (NSString *)JSONFragment {
SBJSON *generator = [[SBJSON new] autorelease];
NSError *error;
NSString *json = [generator stringWithFragment:self error:&error];
if (!json)
NSLog(@"%@", error);
return json;
}
- (NSString *)JSONRepresentation {
SBJSON *generator = [[SBJSON new] autorelease];
NSError *error;
NSString *json = [generator stringWithObject:self error:&error];
if (!json)
NSLog(@"%@", error);
return json;
}
@end
|
zzj9008-aaa
|
Classes/NSObject+SBJSON.m
|
Objective-C
|
asf20
| 2,081
|
//
// ImapSync.h
// ReMailIPhone
//
// Created by Gabor Cselle on 7/15/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <Foundation/Foundation.h>
@interface ImapSync : NSObject {
int accountNum;
}
@property (assign) int accountNum;
-(void)run;
+(NSString*)validate:(NSString*)username password:(NSString*)password server:(NSString*)server port:(int)port encryption:(int)encryption authentication:(int)authentication folders:(NSMutableArray*)folders;
@end
|
zzj9008-aaa
|
Classes/ImapSync.h
|
Objective-C
|
asf20
| 1,031
|
//
// ContactDBAccessor.h
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#import "AddEmailDBAccessor.h" // for SQLite3 constants
#import <objc/runtime.h>
#import <objc/message.h>
@interface ContactDBAccessor : NSObject {
@private
sqlite3 *database;
}
- (NSString *)databaseFilepath;
+ (id)sharedManager;
+ (BOOL)beginTransaction;
+ (BOOL)endTransaction;
- (sqlite3 *)database;
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode;
- (void)setCacheSize:(NSUInteger)pages;
- (void)setLockingMode:(SQLITE3LockingMode)mode;
- (void)deleteDatabase;
- (void)vacuum;
@end
|
zzj9008-aaa
|
Classes/ContactDBAccessor.h
|
Objective-C
|
asf20
| 1,464
|
//
// StoreViewController.m
// ReMailIPhone
//
// Created by Gabor Cselle on 11/11/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// TODO(gabor): NEED TO LOCALIZE STRINGS IN HERE!!!
#import "StoreViewController.h"
#import "StoreItemViewController.h"
#import "StoreObserver.h"
#import "BuchheitTimer.h"
#import "AppSettings.h"
#import "ReMailAppDelegate.h"
#import "StoreItemCell.h"
#import "LoadingCell.h"
@implementation StoreViewController
@synthesize products;
- (void)dealloc {
[super dealloc];
[products release];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)requestProductData {
NSSet* pidsToSell = [NSSet setWithObjects:@"RM_NOADS", @"RM_IMAP", @"RM_RACKSPACE", nil];
SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:pidsToSell];
request.delegate = self;
[request start];
}
-(void)reloadProducts {
[self.tableView reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
StoreObserver* so = [StoreObserver getSingleton];
so.delegate = self;
[self requestProductData];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
StoreObserver* so = [StoreObserver getSingleton];
so.delegate = self;
[self reloadProducts];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (![SKPaymentQueue canMakePayments]) {
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"In-App Purchases Disabled", nil)
message:NSLocalizedString(@"You need to enable in-app purchases in Home > Settings > General > Restrictions to buy features", nil)
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alertView show];
[self.navigationController popViewControllerAnimated:YES];
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0) {
if(self.products == nil) {
return 1;
} else {
return [self.products count];
}
} else { // section == 1
return 1;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
switch(section) {
case 0:
return NSLocalizedString(@"Features to Buy", nil);
case 1:
return NSLocalizedString(@"Restore Purchases", nil);
default:
return @"";
}
}
-(LoadingCell*)createLoadingCellFromNib {
NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"LoadingCell" owner:self options:nil];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
LoadingCell* cell = nil;
NSObject* nibItem = nil;
while ((nibItem = [nibEnumerator nextObject]) != nil) {
if([nibItem isKindOfClass: [LoadingCell class]]) {
cell = (LoadingCell*)nibItem;
break;
}
}
return cell;
}
-(StoreItemCell*)createStoreItemCellFromNib {
NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"StoreItemCell" owner:self options:nil];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
StoreItemCell* cell = nil;
NSObject* nibItem = nil;
while ((nibItem = [nibEnumerator nextObject]) != nil) {
if([nibItem isKindOfClass: [StoreItemCell class]]) {
cell = (StoreItemCell*)nibItem;
break;
}
}
return cell;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 0) {
if(self.products == nil) {
static NSString *CellIdentifier = @"LoadingCell";
LoadingCell *cell = (LoadingCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self createLoadingCellFromNib];
}
[cell.activityIndicator startAnimating];
cell.label.text = NSLocalizedString(@"Loading Products ...", nil);
return cell;
} else {
static NSString *CellIdentifier = @"StoreItemCell";
StoreItemCell *cell = (StoreItemCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self createStoreItemCellFromNib];
}
SKProduct* product = [self.products objectAtIndex:indexPath.row];
UIImage* image = [UIImage imageNamed:[NSString stringWithFormat:@"featureIcon%@.png", product.productIdentifier]];
cell.productIcon.image = image;
cell.titleLabel.text = product.localizedTitle;
if([AppSettings featurePurchased:product.productIdentifier]) {
[cell.priceLabel setHidden:YES];
[cell.purchasedIcon setHidden:NO];
} else {
[cell.priceLabel setHidden:NO];
[cell.purchasedIcon setHidden:YES];
cell.detailTextLabel.backgroundColor = [UIColor yellowColor];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:product.priceLocale];
NSString *formattedString = [numberFormatter stringFromNumber:product.price];
cell.priceLabel.text = formattedString;
}
return cell;
}
} else {
static NSString *CellIdentifier = @"RestoreCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = NSLocalizedString(@"Restore Purchases", nil);
cell.detailTextLabel.text = NSLocalizedString(@"Recover your purchases from prior installs.", nil);
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.section == 1) {
// Use iTunes Connect restoreTransaction
NSLog(@"Restore transactions ...");
UIApplication* app = [UIApplication sharedApplication];
ReMailAppDelegate* appDelegate = app.delegate;
[appDelegate pingHome];
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
} else {
if(self.products == nil) {
// Product list not loaded yet!
return;
}
SKProduct* product = [self.products objectAtIndex:indexPath.row];
if([AppSettings featurePurchased:product.productIdentifier]) {
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Already Purchased", nil)
message:NSLocalizedString(@"This feature has already been purchased.", nil)
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alertView show];
return;
}
StoreItemViewController *vc = [[StoreItemViewController alloc] initWithNibName:@"StoreItem" bundle:nil];
vc.title = product.localizedTitle;
vc.product = product;
[self.navigationController pushViewController:vc animated:YES];
[vc release];
}
}
#pragma mark StoreObserver delegate stuff
-(void)showError:(NSError*)error {
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:error.localizedDescription
message:error.localizedFailureReason
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alertView show];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
if(response.products == nil || [response.products count] == 0) {
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Product List Error", nil)
message:NSLocalizedString(@"Error loading product list from the iTunes server.", nil)
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alertView show];
}
NSMutableArray* a = [NSMutableArray arrayWithArray:response.products];
NSSortDescriptor* desc = [[[NSSortDescriptor alloc] initWithKey:@"price" ascending:NO] autorelease];
NSSortDescriptor* desc2 = [[[NSSortDescriptor alloc] initWithKey:@"productIdentifier" ascending:YES] autorelease];
[a sortUsingDescriptors:[NSArray arrayWithObjects:desc, desc2, nil]];
NSLog(@"Products count: %i", [response.products count]);
self.products = a;
[self reloadProducts];
[request autorelease];
}
-(void)restoreComplete {
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Restore Complete", nil)
message:NSLocalizedString(@"Your purchases have been restored!", nil)
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alertView show];
[self reloadProducts];
}
@end
|
zzj9008-aaa
|
Classes/StoreViewController.m
|
Objective-C
|
asf20
| 9,373
|
//
// MailViewController.m
// ReMailIPhone
//
// Created by Gabor Cselle on 1/13/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "MailViewController.h"
#import "Email.h"
#import "DateUtil.h"
#import "SyncManager.h"
#import "SearchRunner.h"
#import "NSString+SBJSON.h"
#import "AppSettings.h"
#import "AttachmentViewController.h"
#import "AttachmentDownloader.h"
#import "BuchheitTimer.h"
#import "EmailProcessor.h"
@interface MailViewController (Private)
-(UIImageView*)createLine: (CGFloat) y;
@end
@implementation MailViewController (Private)
-(UIImageView*)createLine: (CGFloat) y {
CGFloat contentWidth = self.scrollView.size.width;
UIImageView* line = [[[UIImageView alloc] init] autorelease];
line.backgroundColor = [UIColor darkGrayColor];
line.frame = CGRectMake(0,y,contentWidth,1);
line.autoresizingMask = UIViewAutoresizingFlexibleWidth;
return line;
}
@end
@interface PersonActionSheetHandler : NSObject<UIActionSheetDelegate> {
NSString* name;
NSString* address;
MailViewController* mailVC;
}
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSString* address;
@property (nonatomic, retain) MailViewController* mailVC;
@end
@implementation PersonActionSheetHandler
@synthesize name;
@synthesize address;
@synthesize mailVC;
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) { //Compose Email To
[self.mailVC composeViewWithSubject:@"" body:@"" to:[NSArray arrayWithObject:self.address] cc:nil includeAttachments:NO];
} else if (buttonIndex == 1) { // Copy Address
UIPasteboard* pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard.string = self.address;
} else if (buttonIndex == 2) { // Copy Name
UIPasteboard* pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard.string = self.name;
}
}
@end
@implementation MailViewController
@synthesize emailPk;
@synthesize dbNum;
@synthesize attachmentMetadata;
@synthesize email;
@synthesize copyMode;
@synthesize isSenderSearch;
@synthesize query;
@synthesize unreadIndicator;
@synthesize scrollView;
@synthesize fromLabel;
@synthesize toLabel;
@synthesize ccLabel;
@synthesize replyButton;
@synthesize subjectLabel;
@synthesize dateLabel;
@synthesize deleteDelegate;
@synthesize copyModeButton;
@synthesize copyModeLabel;
@synthesize subjectTTLabel;
@synthesize bodyTTLabel;
@synthesize subjectUIView;
@synthesize bodyUIView;
- (void)dealloc {
[email release];
[fromLabel release];
[toLabel release];
[ccLabel release];
[scrollView release];
[replyButton release];
[copyModeButton release];
[copyModeLabel release];
[subjectLabel release];
[dateLabel release];
[unreadIndicator release];
[attachmentMetadata release];
[subjectTTLabel release];
[bodyTTLabel release];
[subjectUIView release];
[bodyUIView release];
[super dealloc];
}
- (void)viewDidUnload {
[super viewDidUnload];
self.email = nil;
self.fromLabel = nil;
self.toLabel = nil;
self.ccLabel = nil;
self.scrollView = nil;
self.replyButton = nil;
self.copyModeButton = nil;
self.copyModeLabel = nil;
self.subjectLabel = nil;
self.dateLabel = nil;
self.unreadIndicator = nil;
self.subjectTTLabel = nil;
self.bodyTTLabel = nil;
self.subjectUIView = nil;
self.bodyUIView = nil;
self.attachmentMetadata = nil;
}
-(void)personButtonClicked:(TTButton*)target {
NSString *name = [target titleForState:UIControlStateNormal];
NSString *address = [target titleForState:UIControlStateDisabled];
NSString* title = address;
if (![name isEqualToString:address]) {
title = [NSString stringWithFormat:@"%@ <%@>", name, address];
}
PersonActionSheetHandler* pash = [[PersonActionSheetHandler alloc] init]; // this doesn't get released but the actionsheet does not retain it either!
pash.name = name;
pash.address = address;
pash.mailVC = self;
UIActionSheet* aS = [[[UIActionSheet alloc] initWithTitle:title delegate:pash cancelButtonTitle:NSLocalizedString(@"Cancel",nil) destructiveButtonTitle:nil otherButtonTitles:
NSLocalizedString(@"Compose Email To",nil), NSLocalizedString(@"Copy Address",nil), NSLocalizedString(@"Copy Name",nil), nil] autorelease];
[aS showInView:self.view];
}
- (IBAction)replyButtonWasPressed {
UIActionSheet* aS = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel",nil) destructiveButtonTitle:NSLocalizedString(@"Delete", nil) otherButtonTitles:NSLocalizedString(@"Reply", nil),
NSLocalizedString(@"Reply All", nil),
NSLocalizedString(@"Forward", nil),
nil];
[aS showInView:self.view];
[aS release];
}
-(NSMutableArray*)emailAddressesForJson:(NSString*)json {
if(json == nil || [json length] <= 4) {
return [NSMutableArray array];
}
NSArray* peopleList = [json JSONValue];
NSMutableArray* res = [NSMutableArray arrayWithCapacity:[peopleList count]];
for (NSDictionary* person in peopleList) {
NSString* address = [person objectForKey:@"e"];
if (address != nil && [address length] > 0) {
[res addObject: address];
}
}
return res;
}
-(NSString*)replyString {
if(self.email.body == nil || [self.email.body length] == 0) {
return @"";
}
NSDate* date = [DateUtil datetimeInLocal:self.email.datetime];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString* dateString = [dateFormatter stringFromDate:date];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString* timeString = [dateFormatter stringFromDate:date];
NSString *headerString;
if(self.email.senderName != nil && [self.email.senderName length] > 0) {
headerString = [NSString stringWithFormat:@"On %@ at %@, %@ <%@> wrote:", dateString, timeString, self.email.senderName, self.email.senderAddress];
} else {
headerString = [NSString stringWithFormat:@"On %@ at %@, %@ wrote:", dateString, timeString, self.email.senderAddress];
}
NSString* quotedBody = self.email.body;
[dateFormatter release];
if([AppSettings promo]) {
NSString* promoLine = NSLocalizedString(@"I found your email with reMail: http://www.remail.com/s", nil);
return [NSString stringWithFormat:@"\n\n%@\n\n%@\n%@", promoLine, headerString, quotedBody];
} else {
return [NSString stringWithFormat:@"\n\n%@\n%@", headerString, quotedBody];
}
}
-(NSArray*)replyAllRecipients {
NSMutableArray* recipients = [self emailAddressesForJson:self.email.tos];
[recipients addObjectsFromArray:[self emailAddressesForJson:self.email.ccs]];
[recipients addObjectsFromArray:[self emailAddressesForJson:self.email.bccs]];
return recipients;
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) { // Delete
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Delete Message?",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil] autorelease];
[alertView show];
return;
}
BOOL keepSubject = NO;
if(self.email.subject != nil && [self.email.subject length] >= 3) {
NSString* subjectStart = [[self.email.subject substringToIndex:3] lowercaseString];
if([subjectStart isEqualToString:@"r:"] ||
[subjectStart isEqualToString:@"re:"] ||
[subjectStart isEqualToString:@"aw:"]) {
// If the subject line already starts with "Re:", don't edit it
// (that's equivalent to Gmail's behavior
keepSubject = YES;
}
}
if(buttonIndex == 1) { //Reply
NSString* newSubject = self.email.subject;
if(!keepSubject) {
newSubject = [NSString stringWithFormat:@"Re: %@", self.email.subject];
}
[self composeViewWithSubject:newSubject
body:[self replyString]
to:[NSArray arrayWithObject:self.email.senderAddress]
cc:nil
includeAttachments:NO];
} else if (buttonIndex == 2) { // Reply All
NSString* newSubject = self.email.subject;
if(!keepSubject) {
newSubject = [NSString stringWithFormat:@"RE: %@", self.email.subject];
}
[self composeViewWithSubject:newSubject
body:[self replyString]
to:[NSArray arrayWithObject:self.email.senderAddress]
cc:[self replyAllRecipients]
includeAttachments:NO]; //TODO(gabor): Look into In-Reply-To header
} else if (buttonIndex == 3) { // Forward
[self composeViewWithSubject:[NSString stringWithFormat:@"Fwd: %@", self.email.subject]
body:[self replyString]
to:nil
cc:nil
includeAttachments:YES];
} else if (buttonIndex == 0) { // Delete
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Delete Message?",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil] autorelease];
[alertView show];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissModalViewControllerAnimated:YES];
return;
}
-(void)addAttachments:(MFMailComposeViewController*)mailCtrl {
NSFileManager *fileManager = [NSFileManager defaultManager];
for (int i = 0; i < [self.attachmentMetadata count]; i++) {
NSDictionary* attachment = [self.attachmentMetadata objectAtIndex:i];
NSString* filename = [attachment objectForKey:@"n"];
NSString* contentType = [attachment objectForKey:@"t"];
if(filename == nil || [filename length] == 0) {
continue;
}
int accountNumDC = [EmailProcessor accountNumForCombinedFolderNum:self.email.folderNum];
int folderNumDC = [EmailProcessor folderNumForCombinedFolderNum:self.email.folderNum];
NSString* filenameOnDisk = [AttachmentDownloader fileNameForAccountNum:accountNumDC folderNum:folderNumDC uid:self.email.uid attachmentNum:i];
NSString* attachmentDir = [AttachmentDownloader attachmentDirPath];
NSString* attachmentPath = [attachmentDir stringByAppendingPathComponent:filenameOnDisk];
BOOL fileExists = [fileManager fileExistsAtPath:attachmentPath];
if(!fileExists) {
continue;
}
NSData* data = [[NSData alloc] initWithContentsOfFile:attachmentPath];
[mailCtrl addAttachmentData:data mimeType:contentType fileName:filename];
[data release];
i++;
}
}
-(void)composeViewWithSubject:(NSString*)subject body:(NSString*)body to:(NSArray*)to cc:(NSArray*)cc includeAttachments:(BOOL)includeAttachments {
if ([MFMailComposeViewController canSendMail] != YES) {
//TODO(gabor): Show warning - this device is not configured to send email.
return;
}
MFMailComposeViewController *mailCtrl = [[MFMailComposeViewController alloc] init];
if(to != nil && [to count] > 0) {
[mailCtrl setToRecipients:to];
}
if(cc != nil && [cc count] > 0) {
[mailCtrl setCcRecipients:cc];
}
[mailCtrl setSubject:subject];
[mailCtrl setMessageBody:body isHTML:NO];
mailCtrl.mailComposeDelegate = self;
if(includeAttachments) {
[self addAttachments:mailCtrl];
}
[self presentModalViewController:mailCtrl animated:YES];
[mailCtrl release];
}
-(void)attachmentButtonClicked:(TTButton*)target {
NSArray* attachmentList = [email.attachments JSONValue];
NSString* contentType = [[attachmentList objectAtIndex:target.tag] objectForKey:@"t"];
NSString* filename = [[attachmentList objectAtIndex:target.tag] objectForKey:@"n"];
SyncManager* sm = [SyncManager getSingleton];
AttachmentViewController* avc = [[AttachmentViewController alloc] initWithNibName:@"Attachment" bundle:nil];
avc.folderNum = [EmailProcessor folderNumForCombinedFolderNum:self.email.folderNum];
avc.accountNum = [EmailProcessor accountNumForCombinedFolderNum:self.email.folderNum];
avc.attachmentNum = target.tag;
avc.uid = self.email.uid;
avc.contentType = [sm correctContentType:contentType filename:filename];
[avc doLoad];
[self.navigationController pushViewController:avc animated:YES];
[avc release];
}
#pragma mark Handle deletions
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
NSLog(@"Deleting message!");
[Email deleteWithPk:self.emailPk];
if(self.deleteDelegate != nil && [deleteDelegate respondsToSelector:@selector(emailDeleted:)]) {
[deleteDelegate performSelectorOnMainThread:@selector(emailDeleted:) withObject:[NSNumber numberWithInt:self.emailPk] waitUntilDone:NO];
}
[self.navigationController popViewControllerAnimated:YES];
}
}
#pragma mark Assemble UI
-(int)peopleList:(NSString*)title addToView:(UIView*)addToView peopleList:(NSArray*)peopleList top:(int)top highlightAll:(BOOL)highlightAll highlightQuery:(NSString*)highlightQuery {
// produces a list of people name buttons
UIView* toView = [[[UIView alloc] init] autorelease];
toView.frame = CGRectMake(0,top,320,100);
UILabel* labelTo = [[[UILabel alloc] init] autorelease];
labelTo.font = [UIFont systemFontOfSize:14];
labelTo.textColor = [UIColor darkGrayColor];
labelTo.text = title;
CGSize size = [title sizeWithFont:labelTo.font];
labelTo.frame = CGRectMake(0, 0, size.width+2, 30);
[toView addSubview:labelTo];
for (NSDictionary* person in peopleList) {
NSString* name = [person objectForKey:@"n"];
NSString* address = [person objectForKey:@"e"];
NSString* display = nil;
if(name != nil && [name length] > 0) {
display = name;
} else if (address != nil && [address length] > 0) {
display = address;
}
BOOL highlightMatch = NO;
if(highlightQuery != nil) {
highlightMatch = (name != nil && [self matchText:name withQuery:query]) || (address != nil && [self matchText:address withQuery:query]);
}
TTButton* button;
if(highlightAll || highlightMatch) {
button = [TTButton buttonWithStyle:@"redRoundButton:" title:display];
} else {
button = [TTButton buttonWithStyle:@"blueRoundButton:" title:display];
}
button.font = [UIFont boldSystemFontOfSize:12];
[button setTitle:address forState:UIControlStateDisabled]; // using disabled state to store the email address
[button sizeToFit];
[toView addSubview:button];
[button addTarget:self action:@selector(personButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
[self.scrollView addSubview:toView];
TTFlowLayout* flowLayout = [[[TTFlowLayout alloc] init] autorelease];
flowLayout.padding = 5;
flowLayout.spacing = 2;
CGSize toSize = [flowLayout layoutSubviews:toView.subviews forView:toView];
toView.frame = CGRectMake(0, top, toSize.width, toSize.height);
[addToView addSubview:toView];
UIImageView* line = [self createLine:toView.bottom];
[addToView addSubview:line];
return line.bottom;
}
-(int)attachmentList:(NSString*)title addToView:(UIView*)addToView attachmentList:(NSArray*)attachmentList top:(int)top highlightQuery:(NSString*)highlightQuery {
// produces a list of attachment name buttons
UIView* toView = [[[UIView alloc] init] autorelease];
toView.frame = CGRectMake(0,top,320,100);
UILabel* labelTo = [[[UILabel alloc] init] autorelease];
labelTo.font = [UIFont systemFontOfSize:14];
labelTo.textColor = [UIColor darkGrayColor];
labelTo.text = title;
CGSize size = [title sizeWithFont:labelTo.font];
labelTo.frame = CGRectMake(0, 0, size.width+2, 30);
[toView addSubview:labelTo];
SyncManager* sm = [SyncManager getSingleton];
NSFileManager *fileManager = [NSFileManager defaultManager];
int i = 0;
for (NSDictionary* attachment in attachmentList) {
NSString* filename = [attachment objectForKey:@"n"];
NSString* contentType = [attachment objectForKey:@"t"];
BOOL highlightMatch = NO;
if(highlightQuery != nil) {
highlightMatch = (filename != nil && [self matchText:filename withQuery:query]);
}
int accountNumDC = [EmailProcessor accountNumForCombinedFolderNum:self.email.folderNum];
int folderNumDC = [EmailProcessor folderNumForCombinedFolderNum:self.email.folderNum];
NSString* filenameOnDisk = [AttachmentDownloader fileNameForAccountNum:accountNumDC folderNum:folderNumDC uid:self.email.uid attachmentNum:i];
NSString* attachmentDir = [AttachmentDownloader attachmentDirPath];
NSString* attachmentPath = [attachmentDir stringByAppendingPathComponent:filenameOnDisk];
BOOL fileExists = [fileManager fileExistsAtPath:attachmentPath];
if(filename != nil && [filename length] > 0) {
if([sm isAttachmentViewSupported:contentType filename:filename]) {
TTButton* button;
if(highlightMatch && fileExists) {
button = [TTButton buttonWithStyle:@"redRoundButton:" title:filename];
} else if(highlightMatch) {
button = [TTButton buttonWithStyle:@"lightRedRoundButton:" title:filename];
} else if (fileExists) {
button = [TTButton buttonWithStyle:@"greyRoundButton:" title:filename];
} else {
button = [TTButton buttonWithStyle:@"whiteRoundButton:" title:filename];
}
button.font = [UIFont boldSystemFontOfSize:12];
button.tag = i;
[button sizeToFit];
[toView addSubview:button];
[button addTarget:self action:@selector(attachmentButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
} else {
UILabel* label = [[UILabel alloc] init];
label.text = filename;
label.font = [UIFont boldSystemFontOfSize:12];
if(highlightMatch) {
label.textColor = [UIColor redColor];
} else {
label.textColor = [UIColor darkGrayColor];
}
CGSize size = [filename sizeWithFont:label.font];
label.frame = CGRectMake(0, 0, size.width+2, 30);
[toView addSubview:label];
[label release];
}
}
i++;
}
[self.scrollView addSubview:toView];
TTFlowLayout* flowLayout = [[[TTFlowLayout alloc] init] autorelease];
flowLayout.padding = 5;
flowLayout.spacing = 2;
CGSize toSize = [flowLayout layoutSubviews:toView.subviews forView:toView];
toView.frame = CGRectMake(0, top, toSize.width, toSize.height);
[addToView addSubview:toView];
UIImageView* line = [self createLine:toView.bottom];
[addToView addSubview:line];
return line.bottom;
}
-(void)toggleCopyMode:(UIButton*)button {
NSLog(@"toggleCopyMode");
UIImage* copyIcon = nil;
if(self.copyMode) {
self.copyMode = NO;
copyIcon = [UIImage imageNamed:@"copyModeOff.png"];
[self.subjectTTLabel setHidden:NO];
[self.bodyTTLabel setHidden:NO];
[self.subjectUIView setHidden:YES];
[self.bodyUIView setHidden:YES];
[self.copyModeLabel setHidden:YES];
} else {
copyIcon = [UIImage imageNamed:@"copyModeOn.png"];
self.copyMode = YES;
[self.subjectTTLabel setHidden:YES];
[self.bodyTTLabel setHidden:YES];
[self.subjectUIView setHidden:NO];
[self.bodyUIView setHidden:NO];
[self.copyModeLabel setHidden:NO];
}
[button setImage:copyIcon forState:UIControlStateNormal];
[button setImage:copyIcon forState:UIControlStateHighlighted];
[button setImage:copyIcon forState:UIControlStateSelected];
}
-(int)subjectBlock:(NSString*)subject markedUp:(NSString*)subjectMarkedUp date:(NSDate*)date top:(int)top addToView:(UIView*)addToView showTTView:(BOOL)showTTView {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
top += 1;
if(showTTView) {
self.subjectTTLabel = [[[TTStyledTextLabel alloc] initWithFrame:CGRectMake(5, top, 320-65-5, 21)] autorelease];
self.subjectTTLabel.font = [UIFont boldSystemFontOfSize:17];
self.subjectTTLabel.textColor = [UIColor blackColor];
self.subjectTTLabel.text = [TTStyledText textFromXHTML:subjectMarkedUp lineBreaks:NO URLs:NO];
[addToView addSubview:self.subjectTTLabel];
}
CGRect subjectUIRect = CGRectMake(-3, top, 320-10, 21);
if(showTTView) {
subjectUIRect = CGRectMake(-3, top, 320-62-10, 21);
}
self.subjectUIView = [[[UITextView alloc] initWithFrame:subjectUIRect] autorelease];
self.subjectUIView.font = [UIFont boldSystemFontOfSize:17];
self.subjectUIView.textColor = [UIColor blackColor];
self.subjectUIView.text = subject;
self.subjectUIView.scrollEnabled = YES;
self.subjectUIView.editable = NO;
self.subjectUIView.dataDetectorTypes = UIDataDetectorTypeAll;
self.subjectUIView.contentInset = UIEdgeInsetsMake(0,0,0,0);
self.subjectUIView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.subjectUIView setContentOffset:CGPointMake(0,8) animated:NO];
if(showTTView) { //only hide when we're showing the TT view as well
[self.subjectUIView setHidden:YES];
}
[addToView addSubview:self.subjectUIView];
UILabel* labelDate = [[[UILabel alloc] initWithFrame:CGRectMake(5, top+22, 250, 17)] autorelease];
labelDate.font = [UIFont systemFontOfSize:12];
labelDate.textColor = [UIColor darkGrayColor];
labelDate.text = [dateFormatter stringFromDate:date];
[addToView addSubview:labelDate];
UIImageView* line = [self createLine: labelDate.bottom+1] ;
[addToView addSubview:line];
if(showTTView) {
self.copyModeLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.subjectTTLabel.right-1, top+22, 61, 17)] autorelease];
self.copyModeLabel.font = [UIFont systemFontOfSize:12];
self.copyModeLabel.textColor = [UIColor blueColor];
self.copyModeLabel.text = NSLocalizedString(@"Copy Mode", nil);
self.copyModeLabel.adjustsFontSizeToFitWidth = YES;
self.copyModeLabel.textAlignment = UITextAlignmentCenter;
[addToView addSubview:self.copyModeLabel];
[self.copyModeLabel setHidden:YES];
UIImage* copyIcon = [UIImage imageNamed:@"copyModeOff.png"];
self.copyModeButton = [[[UIButton alloc] initWithFrame:CGRectMake(self.subjectTTLabel.right-1,top,62,21)] autorelease];
[self.copyModeButton setImage:copyIcon forState:UIControlStateNormal];
[self.copyModeButton setImage:copyIcon forState:UIControlStateHighlighted];
[self.copyModeButton setImage:copyIcon forState:UIControlStateSelected];
[self.copyModeButton addTarget:self action:@selector(toggleCopyMode:) forControlEvents:UIControlEventTouchUpInside];
[addToView addSubview:self.copyModeButton];
}
[dateFormatter release];
return line.bottom;
}
-(int)bodyBlock:(NSString*)body markedUp:(NSString*)bodyMarkedUp top:(int)top addToView:(UIView*)addToView showTTView:(BOOL)showTTView {
// not showing the TT view is an optimization for when we don't have any markup to show
if(showTTView) {
self.bodyTTLabel = [[[TTStyledTextLabel alloc] initWithFrame:CGRectMake(5, top+8, 310, 100)] autorelease];
self.bodyTTLabel.font = [UIFont systemFontOfSize:14];
self.bodyTTLabel.textColor = [UIColor blackColor];
}
CGFloat contentWidth = self.scrollView.size.width;
self.bodyUIView = [[[UITextView alloc] initWithFrame:CGRectMake(-3, top, 382, 100)] autorelease];
self.bodyUIView.font = [UIFont systemFontOfSize:14];
self.bodyUIView.textColor = [UIColor blackColor];
self.bodyUIView.scrollEnabled = NO;
self.bodyUIView.editable = NO;
self.bodyUIView.dataDetectorTypes = UIDataDetectorTypeAll;
self.bodyUIView.text = body;
self.bodyUIView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[addToView addSubview:self.bodyUIView];
if(showTTView) {
self.bodyTTLabel.text = [TTStyledText textFromXHTML:bodyMarkedUp lineBreaks:YES URLs:YES];
[self.bodyTTLabel sizeToFit];
}
int bottom = 0;
if(showTTView) {
self.bodyUIView.frame = CGRectMake(-3, top, contentWidth, self.bodyTTLabel.bottom-top);
[self.bodyUIView setHidden:YES];
bottom = self.bodyTTLabel.bottom;
[addToView addSubview:self.bodyTTLabel];
} else {
CGSize size = [body sizeWithFont:self.bodyUIView.font constrainedToSize:CGSizeMake(300.0f,100000000.0f) lineBreakMode: UILineBreakModeWordWrap];
self.bodyUIView.frame = CGRectMake(-3, top, contentWidth, size.height+24);
bottom = self.bodyUIView.bottom;
}
return bottom;
}
-(void)loadEmail {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
self.email = [[SearchRunner getSingleton] loadEmail:self.emailPk dbNum:self.dbNum];
[self performSelectorOnMainThread:@selector(loadedEmail) withObject:nil waitUntilDone:NO];
[pool release];
}
-(void)loadedEmail {
// now that the email was loaded (in a different thread), we can display its contents
// remove loading indicator
for(UIView* subview in self.scrollView.subviews) {
if([subview class] == [UILabel class] || [subview class] == [UIActivityIndicatorView class]) {
[subview removeFromSuperview];
}
}
if(self.email == nil) {
int bottom = [self bodyBlock:@"Error: Email not found" markedUp:@"Error: Email not found" top:0 addToView:self.scrollView showTTView:NO];
self.scrollView.contentSize = CGSizeMake(320, bottom+2);
return;
}
NSString *highlightQuery = nil;
if(!self.isSenderSearch) { // only highlight matching senders when we're not in senderSearch
highlightQuery = self.query;
}
BOOL markupBody = YES; // avoid showing the huge TTView for the body if possible
if(self.isSenderSearch || [highlightQuery length] == 0) {
markupBody = NO;
}
NSDictionary* senderDict = [NSDictionary dictionaryWithObjectsAndKeys:email.senderAddress, @"e", email.senderName, @"n", nil];
int bottom = [self peopleList:NSLocalizedString(@"From:",nil) addToView:self.scrollView peopleList:[NSArray arrayWithObject:senderDict] top:0 highlightAll:self.isSenderSearch highlightQuery:highlightQuery];
if(email.tos != nil && [email.tos length] > 4) {
NSArray* peopleList = [email.tos JSONValue];
bottom = [self peopleList:NSLocalizedString(@"To:",nil) addToView:self.scrollView peopleList:peopleList top:bottom highlightAll:NO highlightQuery:highlightQuery];
}
if(email.ccs != nil && [email.ccs length] > 4) {
NSArray* peopleList = [email.ccs JSONValue];
bottom = [self peopleList:NSLocalizedString(@"Cc:",nil) addToView:self.scrollView peopleList:peopleList top:bottom highlightAll:NO highlightQuery:highlightQuery];
}
if(email.bccs != nil && [email.bccs length] > 4) {
NSArray* peopleList = [email.bccs JSONValue];
bottom = [self peopleList:NSLocalizedString(@"Bcc:",nil) addToView:self.scrollView peopleList:peopleList top:bottom highlightAll:NO highlightQuery:highlightQuery];
}
NSString* subject = [self massageDisplayString:email.subject];
if(subject == nil || [subject length] == 0) {
subject = NSLocalizedString(@"[empty]", nil);
email.subject = subject;
}
NSString* subjectMarkup = [self markupText:subject query:highlightQuery beginDelim:@"<span class=\"yellowBox\">" endDelim:@"</span>"];
bottom = [self subjectBlock:email.subject markedUp:subjectMarkup date:email.datetime top:bottom addToView:self.scrollView showTTView:markupBody];
self.attachmentMetadata = nil;
if(email.attachments != nil && [email.attachments length] > 4) {
NSArray* attachmentList = [email.attachments JSONValue];
self.attachmentMetadata = attachmentList;
bottom = [self attachmentList:NSLocalizedString(@"Attachments:",nil) addToView:self.scrollView attachmentList:attachmentList top:bottom highlightQuery:highlightQuery];
}
NSString* body = [self massageDisplayString:email.body];
if(body == nil || [body length] == 0 || [body isEqualToString:@"\r\n"]) {
body = NSLocalizedString(@"[empty]", nil);
}
NSString* bodyMarkup = [self markupText:body query:highlightQuery beginDelim:@"<span class=\"yellowBox\">" endDelim:@"</span>"];
bottom = [self bodyBlock:email.body markedUp:bodyMarkup top:bottom addToView:self.scrollView showTTView:markupBody];
////////////////////
self.scrollView.contentSize = CGSizeMake(320, bottom+2);
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
if(!loaded) {
NSThread *driverThread = [[NSThread alloc] initWithTarget:self selector:@selector(loadEmail) object:nil];
[driverThread start];
[driverThread release];
loaded = YES;
}
// hide toolbar so we have more space to display mail
[self.navigationController setToolbarHidden:YES animated:animated];
}
- (void)loadView {
self.view = [[[[UIView class] alloc] initWithFrame:CGRectMake(0,0,320,480)] autorelease];
self.view.backgroundColor = [UIColor blackColor];
// This is our real view, dude
self.scrollView = [[[[UIScrollView class] alloc] initWithFrame:CGRectMake(0,0,320,480)] autorelease];
self.scrollView.backgroundColor = [UIColor whiteColor];
self.scrollView.canCancelContentTouches = NO;
self.scrollView.showsVerticalScrollIndicator = YES;
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.alwaysBounceVertical = YES;
[self.view addSubview:self.scrollView];
UIActivityIndicatorView* loadingIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(100, 160, 20, 20)];
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
loadingIndicator.hidesWhenStopped = NO;
[self.scrollView addSubview:loadingIndicator];
[loadingIndicator startAnimating];
[loadingIndicator release];
UILabel* loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(127, 160, 90, 20)];
loadingLabel.font = [UIFont systemFontOfSize:14];
loadingLabel.textColor = [UIColor darkGrayColor];
loadingLabel.text = NSLocalizedString(@"Loading email", nil);
[self.scrollView addSubview:loadingLabel];
[loadingLabel release];
self.scrollView.contentSize = CGSizeMake(320, 180);
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.title = @"eMail";
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(replyButtonWasPressed)] autorelease];
}
#pragma mark String massinging and match markup
-(NSString*)massageDisplayString:(NSString*)y {
y = [y stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
y = [y stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
y = [y stringByReplacingOccurrencesOfString:@">" withString:@">"];
return y;
}
-(NSString*)markupText:(NSString*)text query:(NSString*)queryLocal beginDelim:(NSString*)beginDelim endDelim:(NSString*)endDelim {
if(queryLocal == nil) {
return text;
}
if(text == nil) {
return @"";
}
NSMutableString* markedUp = [[NSMutableString alloc] initWithString:text];
NSCharacterSet* beginSet = [NSCharacterSet characterSetWithCharactersInString:@" {}[]()|\"'<\n\r\t^-!;"]; // tries to avoid URL-looking separators
NSCharacterSet* endSet = [NSCharacterSet characterSetWithCharactersInString:@" {}[]()|\"'<\n\r\t^-!;.,:&+#_=~/\\@"]; // it's fine if we end with one of there separators though
NSArray* queryParts = [queryLocal componentsSeparatedByCharactersInSet:endSet];
for(NSString* queryPart in queryParts) {
BOOL star = NO;
if([queryPart hasSuffix:@"*"]) {
star = YES;
queryPart = [queryPart substringToIndex:[queryPart length] - 1];
}
NSRange searchRange = NSMakeRange(0, [markedUp length]);
while(YES) {
NSRange range = [markedUp rangeOfString:queryPart options:NSCaseInsensitiveSearch range:searchRange];
if(range.location == NSNotFound) {
break;
}
BOOL beginOk = NO;
if(range.location == 0) {
beginOk = YES;
} else {
unichar before = [markedUp characterAtIndex:range.location - 1];
beginOk = [beginSet characterIsMember:before];
}
BOOL endOk = NO;
if([markedUp length] == range.location + range.length) {
endOk = YES;
} else if (star) {
NSRange foundSpace = [markedUp rangeOfCharacterFromSet:endSet options:0 range:NSMakeRange(range.location, [markedUp length]-range.location)];
if(foundSpace.location == NSNotFound) {
foundSpace.location = [markedUp length];
}
range = NSMakeRange(range.location, foundSpace.location - range.location);
endOk = YES;
} else {
unichar after = [markedUp characterAtIndex:(range.location + range.length)];
endOk = [endSet characterIsMember:after];
}
if(beginOk && endOk) {
NSString *rangeContents = [markedUp substringWithRange:range];
[markedUp deleteCharactersInRange:range];
[markedUp insertString:[NSString stringWithFormat:@"$$$$beginDelim$$$$%@$$$$endDelim$$$$", rangeContents] atIndex:range.location];
}
searchRange = NSMakeRange(range.location + range.length, [markedUp length] - (range.location + range.length));
}
}
[markedUp replaceOccurrencesOfString:@"$$$$endDelim$$$$" withString:endDelim options:NSLiteralSearch range:NSMakeRange(0,[markedUp length])];
[markedUp replaceOccurrencesOfString:@"$$$$beginDelim$$$$" withString:beginDelim options:NSLiteralSearch range:NSMakeRange(0,[markedUp length])];
NSString* res = [NSString stringWithString:markedUp];
[markedUp release];
return res;
}
-(BOOL)matchText:(NSString*)text withQuery:(NSString*)queryLocal {
NSArray* queryParts = [StringUtil split:queryLocal];
NSCharacterSet* divisor = [NSCharacterSet characterSetWithCharactersInString:@" {}[]()|\"'<\n\r\t^-!;.,:&+#_=~/\\@"];
NSScanner *scanner = [[NSScanner alloc] initWithString:text];
scanner.caseSensitive = NO;
NSString* dest = nil;
NSString* prev = nil;
for(NSString* queryPart in queryParts) {
BOOL star = NO;
if([queryPart hasSuffix:@"*"]) {
star = YES;
queryPart = [queryPart substringToIndex:[queryPart length] - 1];
}
scanner.scanLocation = 0;
BOOL beginOk = NO;
BOOL endOk = NO;
[scanner scanUpToString:queryPart intoString:&prev];
if([scanner scanString:queryPart intoString:&dest]) {
if(prev == nil || [prev length] == 0) {
beginOk = YES;
} else {
unichar c= [prev characterAtIndex:[prev length]-1]; // last character in prev string
beginOk = [divisor characterIsMember:c];
}
if (beginOk) {
if(star) {
// anything goes if we have a star
endOk = YES;
} else {
// no star -> make sure the word ends
if([scanner isAtEnd]) {
endOk = YES;
} else {
unichar c = [text characterAtIndex:scanner.scanLocation];
endOk = [divisor characterIsMember:c];
}
}
}
if(beginOk && endOk) {
[scanner release];
return YES;
}
}
}
[scanner release];
return NO;
}
-(void)viewDidLoad {
loaded = NO;
self.copyMode = NO;
}
#pragma mark View Management
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
NSLog(@"MailViewController received memory warning");
}
#pragma mark Rotation
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
@end
|
zzj9008-aaa
|
Classes/MailViewController.m
|
Objective-C
|
asf20
| 35,091
|
//
// GmailConfigViewController.m
//
// Displays credential entry screen to the user ...
//
// Created by Gabor Cselle on 1/22/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "MailCoreTypes.h"
#import "GmailConfigViewController.h"
#import "ImapSync.h"
#import "AppSettings.h"
#import "HomeViewController.h"
#import "SyncManager.h"
#import "StringUtil.h"
#import "FolderSelectViewController.h"
#import "Reachability.h"
#import "libetpan/mailstorage_types.h"
#import "libetpan/imapdriver_types.h"
#define GMAIL_SERVER @"imap.gmail.com"
#define GMAIL_PORT 993
#define GMAIL_CONNECTION_TYPE CONNECTION_TYPE_TLS
#define GMAIL_AUTH_TYPE IMAP_AUTH_TYPE_PLAIN
@implementation GmailConfigViewController
@synthesize serverMessage, activityIndicator, usernameField, passwordField;
@synthesize firstSetup, accountNum, newAccount;
@synthesize selectFoldersButton;
@synthesize scrollView;
@synthesize privacyNotice;
- (void)dealloc {
[scrollView release];
[serverMessage release];
[activityIndicator release];
[usernameField release];
[passwordField release];
[selectFoldersButton release];
[privacyNotice release];
[super dealloc];
}
- (void)viewDidUnload {
[super viewDidUnload];
self.scrollView = nil;
self.serverMessage = nil;
self.activityIndicator = nil;
self.usernameField = nil;
self.passwordField = nil;
self.selectFoldersButton = nil;
self.privacyNotice = nil;
}
-(void)viewDidLoad {
self.usernameField.delegate = self;
self.passwordField.delegate = self;
// no serverMessage, activityIndicator
self.serverMessage.text = @"";
[self.activityIndicator setHidden:YES];
// preset username, password if they exist
if(!self.newAccount) {
if([AppSettings username:accountNum] != nil) {
self.usernameField.text = [AppSettings username:accountNum];
}
if([AppSettings password:accountNum] != nil) {
self.passwordField.text = [AppSettings password:accountNum];
}
[self.privacyNotice setHidden:YES];
} else {
// if we're adding a new account, we shouldn't show select folders button
[self.selectFoldersButton setHidden:YES];
}
[self.scrollView setContentSize:CGSizeMake(320, 490)];
}
-(void)saveSettings:(NSDictionary*)config {
// The user was editing the account and clicked "Check and Save", and it validated OK
self.serverMessage.text = @"";
[self.activityIndicator setHidden:YES];
[self.activityIndicator stopAnimating];
[AppSettings setAccountType:AccountTypeImap accountNum:self.accountNum];
[AppSettings setUsername:[config objectForKey:@"username"] accountNum:self.accountNum];
[AppSettings setPassword:[config objectForKey:@"password"] accountNum:self.accountNum];
[AppSettings setServerAuthentication:[[config objectForKey:@"authentication"] intValue] accountNum:self.accountNum];
[AppSettings setServer:[config objectForKey:@"server"] accountNum:self.accountNum];
[AppSettings setServerPort:[[config objectForKey:@"port"] intValue] accountNum:self.accountNum];
[AppSettings setServerEncryption:[[config objectForKey:@"encryption"] intValue] accountNum:self.accountNum];
[self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)showFolderSelect:(NSDictionary*)config {
// The user was adding a new account and clicked "Check and Save", now let him/her select folders
self.serverMessage.text = @"";
[self.activityIndicator setHidden:YES];
[self.activityIndicator stopAnimating];
// display home screen
FolderSelectViewController *vc = [[FolderSelectViewController alloc] initWithNibName:@"FolderSelect" bundle:nil];
vc.folderPaths = [config objectForKey:@"folderNames"];
vc.username = [config objectForKey:@"username"];
vc.password = [config objectForKey:@"password"];
vc.server = [config objectForKey:@"server"];
vc.encryption = [[config objectForKey:@"encryption"] intValue];
vc.port = [[config objectForKey:@"port"] intValue];
vc.authentication = [[config objectForKey:@"authentication"] intValue];
vc.newAccount = self.newAccount;
vc.firstSetup = self.firstSetup;
vc.accountNum = self.accountNum;
[self.navigationController pushViewController:vc animated:YES];
[vc release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if(textField == self.usernameField) {
// usernameField -> go to passwordField
[self.passwordField becomeFirstResponder];
return YES;
} else {
// passwordField -> login
[self loginClick];
return YES;
}
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController setToolbarHidden:YES animated:animated];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.selectFoldersButton setEnabled:YES];
}
-(void)failedLoginWithMessage:(NSString*)message {
self.serverMessage.text = message;
[self.activityIndicator stopAnimating];
[self.activityIndicator setHidden:YES];
[self.selectFoldersButton setEnabled:YES];
}
-(void)doLogin:(NSNumber*)forceSelectFolders {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString* username = self.usernameField.text;
NSString* password = self.passwordField.text;
NSString* server = GMAIL_SERVER;
int encryption = GMAIL_CONNECTION_TYPE;
int port = GMAIL_PORT;
int authentication = GMAIL_AUTH_TYPE;
if(![StringUtil stringContains:username subString:@"@"]) {
username = [NSString stringWithFormat:@"%@@gmail.com", username];
}
NSLog(@"Logging in with user %@", username);
NSMutableArray* folderNames = [[[NSMutableArray alloc] initWithCapacity:20] autorelease];
NSString* response = [ImapSync validate:username password:password server:GMAIL_SERVER port:GMAIL_PORT encryption:GMAIL_CONNECTION_TYPE authentication:GMAIL_AUTH_TYPE folders:folderNames];
if([StringUtil stringContains:response subString:@"Parse error"]) {
[[Reachability sharedReachability] setHostName:server];
NetworkStatus status =[[Reachability sharedReachability] remoteHostStatus];
if(status == NotReachable) {
response = NSLocalizedString(@"Email server unreachable", nil);
} else if(status == ReachableViaCarrierDataNetwork) {
response = NSLocalizedString(@"Error connecting to server. Try over Wifi.", nil);
} else {
response = NSLocalizedString(@"Error connecting to server.", nil);
}
} else if([StringUtil stringContains:response subString:CTLoginErrorDesc]) {
response = NSLocalizedString(@"Wrong username or password.", nil);
}
if([response isEqualToString:@"OK"]) {
NSDictionary* localConfig = [NSDictionary dictionaryWithObjectsAndKeys:username, @"username",
password, @"password",
server, @"server",
[NSNumber numberWithInt:encryption], @"encryption",
[NSNumber numberWithInt:port], @"port",
[NSNumber numberWithInt:authentication], @"authentication",
folderNames, @"folderNames", nil];
if(self.newAccount || [forceSelectFolders boolValue]) {
[self performSelectorOnMainThread:@selector(showFolderSelect:) withObject:localConfig waitUntilDone:NO];
} else {
[self performSelectorOnMainThread:@selector(saveSettings:) withObject:localConfig waitUntilDone:NO];
}
} else {
[self performSelectorOnMainThread:@selector(failedLoginWithMessage:) withObject:response waitUntilDone:NO];
}
[pool release];
}
-(BOOL)accountExists:(NSString*)username server:(NSString*)server {
for(int i = 0; i < [AppSettings numAccounts]; i++) {
if([AppSettings accountDeleted:i]) {
continue;
}
if([[AppSettings server:i] isEqualToString:server] && [[AppSettings username:i] isEqualToString:username]) {
return YES;
}
}
return NO;
}
-(IBAction)loginClick {
[self backgroundClick]; // to deactivate all keyboards
// check if account already exists
if(self.newAccount) {
NSString* username = self.usernameField.text;
//TODO(gabor): need to extract and prettify this
if(![StringUtil stringContains:username subString:@"@"]) {
username = [NSString stringWithFormat:@"%@@gmail.com", username];
}
NSString* server = GMAIL_SERVER;
if([self accountExists:username server:server]) {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Account Exists",nil) message:NSLocalizedString(@"reMail already has an account for this username/server combination", nil) delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];
[alertView release];
return;
}
}
self.serverMessage.text = NSLocalizedString(@"Validating login ...", nil);
[self.activityIndicator setHidden:NO];
[self.activityIndicator startAnimating];
NSThread *driverThread = [[NSThread alloc] initWithTarget:self selector:@selector(doLogin:) object:[NSNumber numberWithBool:NO]];
[driverThread start];
[driverThread release];
}
-(IBAction)backgroundClick {
[self.usernameField resignFirstResponder];
[self.passwordField resignFirstResponder];
}
-(IBAction)selectFoldersClicked {
[self.selectFoldersButton setEnabled:NO];
[self.usernameField resignFirstResponder];
[self.passwordField resignFirstResponder];
[self.activityIndicator setHidden:NO];
[self.activityIndicator startAnimating];
NSThread *driverThread = [[NSThread alloc] initWithTarget:self selector:@selector(doLogin:) object:[NSNumber numberWithBool:YES]];
[driverThread start];
[driverThread release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
NSLog(@"GmailConfig received memory warning");
}
@end
|
zzj9008-aaa
|
Classes/GmailConfigViewController.m
|
Objective-C
|
asf20
| 10,080
|
//
// AttachmentViewController.h
// ReMailIPhone
//
// Created by Gabor Cselle on 7/7/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
@interface AttachmentViewController : UIViewController <UIWebViewDelegate> {
IBOutlet UIWebView* webWiew;
IBOutlet UILabel *loadingLabel;
IBOutlet UIActivityIndicatorView* loadingIndicator;
NSString* contentType;
NSString* uid;
int attachmentNum;
int folderNum;
int accountNum;
}
-(void)doLoad;
-(void)deliverAttachment;
-(void)deliverError:(NSString*)error;
@property (nonatomic, retain) UIWebView* webWiew;
@property (nonatomic, retain) UILabel *loadingLabel;
@property (nonatomic, retain) UIActivityIndicatorView* loadingIndicator;
@property (nonatomic, retain) NSString* uid;
@property (nonatomic, retain) NSString* contentType;
@property (assign) int attachmentNum;
@property (assign) int folderNum;
@property (assign) int accountNum;
@end
|
zzj9008-aaa
|
Classes/AttachmentViewController.h
|
Objective-C
|
asf20
| 1,481
|
//
// AccountTypeSelectViewController.h
// ReMailIPhone
//
// Created by Gabor Cselle on 7/15/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
@interface AccountTypeSelectViewController : UIViewController {
BOOL firstSetup;
BOOL showIntro;
BOOL newAccount;
int accountNum;
IBOutlet UILabel* rackspaceLabel;
IBOutlet UIButton* rackspaceButton;
IBOutlet UILabel* imapLabel;
IBOutlet UIButton* imapButton;
IBOutlet UIButton* buyButton;
}
@property (assign) BOOL firstSetup;
@property (assign) BOOL newAccount;
@property (assign) int accountNum;
@property (nonatomic,retain) UILabel* rackspaceLabel;
@property (nonatomic,retain) UIButton* rackspaceButton;
@property (nonatomic,retain) UILabel* imapLabel;
@property (nonatomic,retain) UIButton* imapButton;
@property (nonatomic,retain) UIButton* buyButton;
-(IBAction)gmailClicked;
-(IBAction)rackspaceClicked;
-(IBAction)imapClicked;
-(IBAction)buyClick;
@end
|
zzj9008-aaa
|
Classes/AccountTypeSelectViewController.h
|
Objective-C
|
asf20
| 1,513
|
//
// SettingsListViewController.h
// ReMailIPhone
//
// Created by Gabor Cselle on 9/15/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
@interface SettingsListViewController : UITableViewController <MFMailComposeViewControllerDelegate> {
NSMutableArray* accountIndices; // stores the indices of non-deleted accounts
}
@property (nonatomic, retain) NSMutableArray* accountIndices;
@end
|
zzj9008-aaa
|
Classes/SettingsListViewController.h
|
Objective-C
|
asf20
| 1,009
|
//
// ImapFolderWorker.h
// ReMailIPhone
//
// Created by Gabor Cselle on 6/29/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <Foundation/Foundation.h>
#import "CTCoreFolder.h"
#import "CTCoreAccount.h"
@interface ImapFolderWorker : NSObject {
CTCoreFolder* folder;
CTCoreAccount* account;
int folderNum;
int accountNum;
NSString* folderDisplayName;
NSString* folderPath;
BOOL firstSync;
}
+(NSString*)decodeError:(NSException*)exp;
-(id)initWithFolder:(CTCoreFolder*)folderLocal folderNum:(int)folderNumLocal account:(CTCoreAccount*)accountLocal accountNum:(int)accountNum;
-(BOOL)run;
-(int)backwardScan:(int)newSyncStart;
-(BOOL)newSync:(int)start total:(int)total seqDelta:(int)seqDelta alreadySynced:(int)alreadySynced;
-(BOOL)oldSync:(int)start total:(int)total;
-(BOOL)fetchFrom:(int)start to:(int)end seqDelta:(int)seqDelta syncingNew:(BOOL)syncingNew progressOffset:(int)progressOffset progressTotal:(int)progressTotal alreadySynced:(int)alreadySynced;
@property (nonatomic, retain) CTCoreFolder* folder;
@property (nonatomic, retain) CTCoreAccount* account;
@property (assign) int folderNum;
@property (assign) int accountNum;
@property (nonatomic, retain) NSString* folderDisplayName;
@property (nonatomic, retain) NSString* folderPath;
@property (assign) BOOL firstSync;
@end
|
zzj9008-aaa
|
Classes/ImapFolderWorker.h
|
Objective-C
|
asf20
| 1,875
|
//
// ActivityIndicator.h
// ReMailIPhone
//
// Created by Gabor Cselle on 2/13/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <Foundation/Foundation.h>
@interface ActivityIndicator : NSObject {
}
+(void)on;
+(void)off;
@end
|
zzj9008-aaa
|
Classes/ActivityIndicator.h
|
Objective-C
|
asf20
| 803
|
//
// SyncManager.m
// Remail iPhone
//
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <CommonCrypto/CommonDigest.h>
#import "SyncManager.h"
#import "ActivityIndicator.h"
#import "BuchheitTimer.h"
#import "StringUtil.h"
#import "Reachability.h"
#import "UidDBAccessor.h"
#import "AppSettings.h"
#import "ImapSync.h"
#import "GlobalDBFunctions.h"
#define SYNC_STATE_FILE_NAME_TEMPLATE @"sync_state_%i.plist"
#define FOLDER_STATES_KEY @"folderStates"
static SyncManager *singleton = nil;
@implementation SyncManager
@synthesize progressDelegate;
@synthesize progressNumbersDelegate;
@synthesize clientMessageDelegate;
@synthesize clientMessageWasError;
@synthesize newEmailDelegate;
@synthesize syncStates;
@synthesize syncInProgress;
@synthesize okContentTypes;
@synthesize extensionContentType;
@synthesize lastErrorAccountNum;
@synthesize lastErrorFolderNum;
@synthesize lastErrorStartSeq;
@synthesize skipMessageAccountNum;
@synthesize skipMessageFolderNum;
@synthesize skipMessageStartSeq;
@synthesize lastAbort;
- (void) dealloc {
[progressDelegate release];
[progressNumbersDelegate release];
[clientMessageDelegate release];
[syncStates release];
[okContentTypes release];
[extensionContentType release];
[lastAbort release];
[super dealloc];
}
+ (id)getSingleton { //NOTE: don't get an instance of SyncManager until account settings are set!
@synchronized(self) {
if (singleton == nil) {
singleton = [[self alloc] init];
}
}
return singleton;
}
-(id)init {
if (self = [super init]) {
self.skipMessageAccountNum = -1;
self.skipMessageFolderNum = -1;
self.skipMessageStartSeq = -1;
self.lastErrorAccountNum = -1;
self.lastErrorFolderNum = -1;
self.lastErrorStartSeq = -1;
self.lastAbort = [NSDate distantPast];
self.clientMessageWasError = NO;
//Get the persistent state
self.syncStates = [NSMutableArray arrayWithCapacity:2];
for(int i = 0; i < [AppSettings numAccounts]; i++) {
if([AppSettings accountDeleted:i]) {
[self.syncStates addObject:[NSMutableDictionary dictionaryWithCapacity:1]];
} else {
NSString *filePath = [StringUtil filePathInDocumentsDirectoryForFileName:[NSString stringWithFormat:SYNC_STATE_FILE_NAME_TEMPLATE, i]];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSData *fileData = [[NSData alloc] initWithContentsOfFile:filePath];
NSMutableDictionary* props = [NSPropertyListSerialization propertyListFromData:fileData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:nil errorDescription:nil];
[self.syncStates addObject:props];
[fileData release];
} else {
NSMutableDictionary* props = [[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"2", @"__version", [NSMutableArray array], FOLDER_STATES_KEY, nil] autorelease];
[self.syncStates addObject:props];
}
}
}
}
return self;
}
-(void)runLoop {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[NSThread setThreadPriority:0.1];
@synchronized(self) {
if(self.syncInProgress) {
return;
}
self.syncInProgress = YES;
}
@try {
[ActivityIndicator on]; // turned back off in syncAborted / syncDone
UIApplication* application = [UIApplication sharedApplication];
application.idleTimerDisabled = YES;
[self clearClientMessage];
for(int i = 0; i < [AppSettings numAccounts]; i++) {
if([AppSettings accountDeleted:i]) {
continue;
}
ImapSync* imapSync;
switch([AppSettings accountType:i]) {
case AccountTypeImap:
imapSync = [[ImapSync alloc] init];
imapSync.accountNum = i;
[imapSync run];
[imapSync release];
break;
default:
NSLog(@"Account type currently not supported");
break;
}
}
} @catch(NSException* exp) {
NSLog(@"Exception in runLoop: %@", exp);
} @finally {
[ActivityIndicator off];
UIApplication* application = [UIApplication sharedApplication];
application.idleTimerDisabled = NO;
self.syncInProgress = NO;
[pool release];
}
}
-(void)run {
if(self.syncInProgress) {
return;
}
//Fire the sync in a separate thread
NSThread *driverThread = [[NSThread alloc] initWithTarget:self selector:@selector(runLoop) object:nil];
[driverThread start];
[driverThread release];
}
#pragma mark Request sync
-(BOOL)serverReachable:(int)accountNum {
NSString *checkHost = [AppSettings server:accountNum];
[[Reachability sharedReachability] setHostName:checkHost];
NetworkStatus status =[[Reachability sharedReachability] remoteHostStatus];
if(status != NotReachable) {
return YES;
} else {
return NO;
}
}
- (void) requestSyncIfNoneInProgressAndConnectedThread {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
@try {
//Check there are no push in progres.
if(self.syncInProgress) {
return;
}
BOOL found = NO;
for(int i = 0; i < [AppSettings numAccounts]; i++) {
if(![AppSettings accountDeleted:i]) {
if ([self serverReachable:i]) {
found = YES;
break;
}
}
}
if(!found) {
if([AppSettings numAccounts] > 1) {
[self reportProgressString:NSLocalizedString(@"Email servers unreachable", nil)];
} else {
[self reportProgressString:NSLocalizedString(@"Email server unreachable", nil)];
}
} else {
[self run];
}
} @finally {
[pool release];
}
}
- (void) requestSyncIfNoneInProgressAndConnected {
// This can be called from main thread -> thread off
NSThread *driverThread = [[NSThread alloc] initWithTarget:self selector:@selector(requestSyncIfNoneInProgressAndConnectedThread) object:nil];
[driverThread start];
[driverThread release];
}
-(void)requestSyncIfNoneInProgress {
//Check there are no push in progres.
if(![GlobalDBFunctions enoughFreeSpaceForSync]) {
[self setClientMessage:NSLocalizedString(@"iPhone/iPod disk full", nil) withColor:@"red" withErrorDetail:nil];
[self reportProgressString:NSLocalizedString(@"Sync aborted", nil)];
return;
}
if(self.syncInProgress) {
return;
}
[self run];
}
#pragma mark Update and retrieve syncState
-(int)folderCount:(int)accountNum {
NSArray* folderStates = [[self.syncStates objectAtIndex:accountNum] objectForKey:FOLDER_STATES_KEY];
return [folderStates count];
}
-(NSMutableDictionary*)retrieveState:(int)folderNum accountNum:(int)accountNum {
NSArray* folderStates = [[self.syncStates objectAtIndex:accountNum] objectForKey:FOLDER_STATES_KEY];
if (folderNum >= [folderStates count]) {
return nil;
}
return [folderStates objectAtIndex:folderNum];
}
-(void)addAccountState {
int numAccounts = [AppSettings numAccounts];
NSMutableDictionary* props = [[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"2", @"__version", [NSMutableArray array], FOLDER_STATES_KEY, nil] autorelease];
[self.syncStates addObject:props];
NSString* filePath = [StringUtil filePathInDocumentsDirectoryForFileName:[NSString stringWithFormat:SYNC_STATE_FILE_NAME_TEMPLATE, numAccounts+1]];
if(![[self.syncStates objectAtIndex:numAccounts] writeToFile:filePath atomically:YES]) {
NSLog(@"Unsuccessful in persisting state to file %@", filePath);
}
[AppSettings setNumAccounts:numAccounts+1];
[AppSettings setAccountDeleted:NO accountNum:numAccounts];
}
-(void)addFolderState:(NSMutableDictionary *)data accountNum:(int)accountNum {
NSMutableArray* folderStates = [[self.syncStates objectAtIndex:accountNum] objectForKey:FOLDER_STATES_KEY];
[folderStates addObject:data];
NSString* filePath = [StringUtil filePathInDocumentsDirectoryForFileName:[NSString stringWithFormat:SYNC_STATE_FILE_NAME_TEMPLATE, accountNum]];
if(![[self.syncStates objectAtIndex:accountNum] writeToFile:filePath atomically:YES]) {
NSLog(@"Unsuccessful in persisting state to file %@", filePath);
}
}
-(BOOL)isFolderDeleted:(int)folderNum accountNum:(int)accountNum {
NSArray* folderStates = [[self.syncStates objectAtIndex:accountNum] objectForKey:FOLDER_STATES_KEY];
if (folderNum >= [folderStates count]) {
return YES;
}
NSNumber* y = [[folderStates objectAtIndex:folderNum] objectForKey:@"deleted"];
return (y == nil) || [y boolValue];
}
-(void)markFolderDeleted:(int)folderNum accountNum:(int)accountNum {
NSMutableArray* folderStates = [[self.syncStates objectAtIndex:accountNum] objectForKey:FOLDER_STATES_KEY];
NSMutableDictionary* y = [folderStates objectAtIndex:folderNum];
[y setValue:[NSNumber numberWithBool:YES] forKey:@"deleted"];
NSString* filePath = [StringUtil filePathInDocumentsDirectoryForFileName:[NSString stringWithFormat:SYNC_STATE_FILE_NAME_TEMPLATE, accountNum]];
if(![[self.syncStates objectAtIndex:accountNum] writeToFile:filePath atomically:YES]) {
NSLog(@"Unsuccessful in persisting state to file %@", filePath);
}
}
-(void)persistState:(NSMutableDictionary *)data forFolderNum:(int)folderNum accountNum:(int)accountNum {
NSMutableArray* folderStates = [[self.syncStates objectAtIndex:accountNum] objectForKey:FOLDER_STATES_KEY];
[folderStates replaceObjectAtIndex:folderNum withObject:data];
NSString* filePath = [StringUtil filePathInDocumentsDirectoryForFileName:[NSString stringWithFormat:SYNC_STATE_FILE_NAME_TEMPLATE, accountNum]];
if(![[self.syncStates objectAtIndex:accountNum] writeToFile:filePath atomically:YES]) {
NSLog(@"Unsuccessful in persisting state to file %@", filePath);
}
}
-(int)emailsOnDeviceExceptFor:(int)folderNum accountNum:(int)accountNum {
int total = 0;
for(int a = 0; a < [AppSettings numAccounts]; a++) {
if([AppSettings accountDeleted:a]) {
continue;
}
NSMutableArray* folderStates = [[self.syncStates objectAtIndex:a] objectForKey:FOLDER_STATES_KEY];
for(int i = 0; i < [folderStates count]; i++) {
if(a == accountNum && i == folderNum) {
continue;
}
NSDictionary* folder = [folderStates objectAtIndex:i];
if ([folder objectForKey:@"numSynced"] != nil) {
total += [[folder objectForKey:@"numSynced"] intValue];
}
}
}
return total;
}
-(int)emailsOnDevice {
int total = 0;
for(int a = 0; a < [AppSettings numAccounts]; a++) {
NSMutableArray* folderStates = [[self.syncStates objectAtIndex:a] objectForKey:FOLDER_STATES_KEY];
NSEnumerator* stateEnum = [folderStates objectEnumerator];
NSDictionary* folder = nil;
while(folder = [stateEnum nextObject]) {
if ([folder objectForKey:@"numSynced"] != nil) {
total += [[folder objectForKey:@"numSynced"] intValue];
}
}
}
return total;
}
-(int)emailsInAccounts {
int total = 0;
for(int a = 0; a < [AppSettings numAccounts]; a++) {
if([AppSettings accountDeleted:a]) { // do not count emails from accounts we have deleted
continue;
}
NSMutableArray* folderStates = [[self.syncStates objectAtIndex:a] objectForKey:FOLDER_STATES_KEY];
NSEnumerator* stateEnum = [folderStates objectEnumerator];
NSDictionary* folder = nil;
while(folder = [stateEnum nextObject]) {
if ([folder objectForKey:@"deleted"] != nil && [[folder objectForKey:@"deleted"] boolValue]) {
continue;
}
if ([folder objectForKey:@"folderCount"] != nil) {
total += [[folder objectForKey:@"folderCount"] intValue];
}
}
}
return total;
}
#pragma mark Backchannel for IMAP workers
-(void)clearClientMessage {
self.clientMessageWasError = NO;
[self setClientMessage:nil withColor:nil withErrorDetail:nil];
return;
}
-(void)clearWarning {
if(!self.clientMessageWasError) {
[self setClientMessage:nil withColor:nil withErrorDetail:nil];
}
}
-(void)syncWarning:(NSString*)description {
NSLog(@"Sync warning: %@", description);
self.clientMessageWasError = NO;
[self setClientMessage:description withColor:@"black" withErrorDetail:nil];
return;
}
-(void)syncAborted:(NSString*)reason detail:(NSString*)detail accountNum:(int)accountNum folderNum:(int)folderNum startSeq:(int)startSeq {
self.clientMessageWasError = YES;
self.lastErrorAccountNum = accountNum;
self.lastErrorFolderNum = folderNum;
self.lastErrorStartSeq = startSeq;
NSLog(@"Sync aborted: %@|%@", reason, detail);
[self setClientMessage:reason withColor:@"red" withErrorDetail:detail];
[self reportProgressString:NSLocalizedString(@"Sync aborted",nil)];
NSTimeInterval sinceLastAbort = [self.lastAbort timeIntervalSinceNow];
if(sinceLastAbort < -30.0) {
// timer to restart sync, as that's a good idea for "connection lost" type cases
NSTimer *timer = [NSTimer timerWithTimeInterval:30.0
target: singleton
selector: @selector(requestSyncIfNoneInProgressAndConnected)
userInfo: nil
repeats: NO];
NSRunLoop *curr = [NSRunLoop mainRunLoop];
[curr addTimer: timer forMode: NSRunLoopCommonModes];
self.lastAbort = [NSDate date];
}
return;
}
-(void)syncAborted:(NSString*)reason detail:(NSString*)detail {
[self syncAborted:reason detail:detail accountNum:-1 folderNum:-1 startSeq:-1];
}
-(void)syncDone {
UIApplication* application = [UIApplication sharedApplication];
application.idleTimerDisabled = NO;
[self reportProgressString:nil]; // calling this with nil results in "Updated at 11:19am" being shown on the screen
return;
}
#pragma mark Progress reporting
-(void)reportProgressString:(NSString*)progress {
if(self.progressDelegate != nil && [self.progressDelegate respondsToSelector:@selector(didChangeProgressStringTo:)]) {
[self.progressDelegate performSelectorOnMainThread:@selector(didChangeProgressStringTo:) withObject:progress waitUntilDone:NO];
}
}
-(void)reportProgress:(float)progress withMessage:(NSString*)message {
NSDictionary* progressDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:progress], @"progress", message, @"message", nil];
if(self.progressDelegate != nil && [self.progressDelegate respondsToSelector:@selector(didChangeProgressTo:)]) {
[self.progressDelegate performSelectorOnMainThread:@selector(didChangeProgressTo:) withObject:progressDict waitUntilDone:NO];
}
}
-(void)reportProgressNumbers:(int)total synced:(int)synced folderNum:(int)folderNum accountNum:(int)accountNum {
NSDictionary* progressDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:total], @"total", [NSNumber numberWithInt:synced],
@"synced", [NSNumber numberWithInt:folderNum], @"folderNum", [NSNumber numberWithInt:accountNum], @"accountNum", nil];
if(self.progressNumbersDelegate != nil && [self.progressNumbersDelegate respondsToSelector:@selector(didChangeProgressNumbersTo:)]) {
[self.progressNumbersDelegate performSelectorOnMainThread:@selector(didChangeProgressNumbersTo:) withObject:progressDict waitUntilDone:NO];
}
}
-(void)registerForProgressNumbersWithDelegate:(id) delegate {
//assert([delegate respondsToSelector:@selector(didChangeProgressNumbersTo:)]); // can be reset to zero
self.progressNumbersDelegate = delegate;
}
-(void)registerForProgressWithDelegate:(id) delegate {
assert([delegate respondsToSelector:@selector(didChangeProgressStringTo:)]);
assert([delegate respondsToSelector:@selector(didChangeProgressTo:)]);
self.progressDelegate = delegate;
}
#pragma mark Client Messages
- (void) registerForClientMessageWithDelegate:(id) delegate {
assert([delegate respondsToSelector:@selector(didChangeClientMessageTo:)]);
self.clientMessageDelegate = delegate;
}
-(void)setClientMessage:(NSString*)message withColor:(NSString*)color withErrorDetail:(NSString*)errorDetailLocal {
NSDictionary* dict = nil;
if((message != nil) && (color != nil)) {
dict = [NSDictionary dictionaryWithObjectsAndKeys:message, @"message", color, @"color", errorDetailLocal, @"errorDetail", nil];
}
if(self.clientMessageDelegate != nil && [self.clientMessageDelegate respondsToSelector:@selector(didChangeClientMessageTo:)]) {
[self.clientMessageDelegate performSelectorOnMainThread:@selector(didChangeClientMessageTo:) withObject:dict waitUntilDone:NO];
}
}
#pragma mark New Email notifications
- (void)registerForNewEmail:(id)delegate {
assert([delegate respondsToSelector:@selector(didSyncNewEmail)]);
self.newEmailDelegate = delegate;
}
-(void)triggerNewEmail {
if(self.newEmailDelegate != nil && [self.newEmailDelegate respondsToSelector:@selector(didSyncNewEmail:)]) {
[self.newEmailDelegate performSelectorOnMainThread:@selector(didSyncNewEmail:) withObject:nil waitUntilDone:NO];
}
}
#pragma mark Attachment handling
-(BOOL)isAttachmentViewSupported:(NSString*)contentType filename:(NSString*)filename {
if(self.okContentTypes == nil) {
self.okContentTypes = [NSSet setWithObjects:@"image/gif", @"image/png", @"image/tiff", @"image/jpeg",
@"text/plain", @"text/html", @"text/xml", @"application/pdf", @"application/msword", @"application/vnd.ms-excel", nil];
}
if([self.okContentTypes containsObject:contentType]) {
return YES;
}
// else, return yes if content type gets autocorrected
if(![[self correctContentType:contentType filename:filename] isEqualToString:contentType]) {
return YES;
}
return NO;
}
-(NSString*)correctContentType:(NSString*)contentType filename:(NSString*)filename {
if(self.extensionContentType == nil) {
self.extensionContentType = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain", @"m",
@"text/plain", @"h",
@"text/plain", @"c",
@"text/plain", @"cpp",
@"text/plain", @"py",
@"text/plain", @"rb",
@"text/plain", @"cs",
@"text/plain", @"csv",
@"text/plain", @"java",
@"text/plain", @"txt",
@"text/plain", @"text",
@"text/plain", @"tex", // Latex, as reported by Beta user Kai Kunze
@"image/png", @"png",
@"image/gif", @"gif",
@"image/tiff", @"tiff",
@"image/tiff", @"tif",
@"image/jpeg", @"jpeg",
@"image/jpeg", @"jpg",
@"application/pdf", @"pdf", nil];
}
NSString* extension = [filename pathExtension];
if([self.extensionContentType objectForKey:extension] != nil) {
return [self.extensionContentType objectForKey:extension];
}
return contentType;
}
@end
|
zzj9008-aaa
|
Classes/SyncManager.m
|
Objective-C
|
asf20
| 18,588
|
//
// DateUtil.m
// ReMailIPhone
//
// Created by Gabor Cselle on 3/17/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "DateUtil.h"
#define DATE_UTIL_SECS_PER_DAY 86400
static DateUtil *singleton = nil;
@implementation DateUtil
@synthesize today;
@synthesize yesterday;
@synthesize lastWeek;
@synthesize todayComponents;
@synthesize yesterdayComponents;
@synthesize dateFormatter;
-(void)dealloc {
[today release];
[yesterday release];
[lastWeek release];
[todayComponents release];
[yesterdayComponents release];
[dateFormatter release];
[super dealloc];
}
-(void)refreshData {
//TODO(gabor): Call this every hour or so to refresh what today, yesterday, etc. mean
NSCalendar *gregorian = [NSCalendar currentCalendar];
self.today = [NSDate date];
self.yesterday = [today dateByAddingTimeInterval:-DATE_UTIL_SECS_PER_DAY];
self.lastWeek = [today dateByAddingTimeInterval:-6*DATE_UTIL_SECS_PER_DAY];
self.todayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:today];
self.yesterdayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:yesterday];
self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
}
-(id)init {
if (self = [super init]) {
[self refreshData];
}
return self;
}
+(id)getSingleton { //NOTE: don't get an instance of SyncManager until account settings are set!
@synchronized(self) {
if (singleton == nil) {
singleton = [[self alloc] init];
}
}
return singleton;
}
-(NSString*)humanDate:(NSDate*)date {
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:date];
if([dateComponents day] == [todayComponents day] &&
[dateComponents month] == [todayComponents month] &&
[dateComponents year] == [todayComponents year]) {
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
return [dateFormatter stringFromDate:date];
}
if([dateComponents day] == [yesterdayComponents day] &&
[dateComponents month] == [yesterdayComponents month] &&
[dateComponents year] == [yesterdayComponents year]) {
return NSLocalizedString(@"yesterday", nil);
}
if([date laterDate:lastWeek] == date) {
[dateFormatter setDateFormat:@"EEEE"];
return [dateFormatter stringFromDate:date];
}
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
return [dateFormatter stringFromDate:date];
}
+(NSDate *)datetimeInLocal:(NSDate *)utcDate
{
NSTimeZone *utc = [NSTimeZone timeZoneWithName:@"UTC"];
NSTimeZone *local = [NSTimeZone localTimeZone];
NSInteger sourceSeconds = [utc secondsFromGMTForDate:utcDate];
NSInteger destinationSeconds = [local secondsFromGMTForDate:utcDate];
NSTimeInterval interval = destinationSeconds - sourceSeconds;
NSDate *res = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:utcDate] autorelease];
return res;
}
@end
|
zzj9008-aaa
|
Classes/DateUtil.m
|
Objective-C
|
asf20
| 3,672
|
//
// NextMailAppDelegate.m
// NextMail iPhone Application
//
// Created by Gabor Cselle on 1/16/09.
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "ReMailAppDelegate.h"
#import "Reachability.h"
#import "AppSettings.h"
#import "HomeViewController.h"
#import "HomeViewController.h"
#import "SyncManager.h"
#import "StringUtil.h"
#import "SearchRunner.h"
#import "AccountTypeSelectViewController.h"
#import "GlobalDBFunctions.h"
#import "ActivityIndicator.h"
#import "EmailProcessor.h"
#import "AddEmailDBAccessor.h"
#import "SearchEmailDBAccessor.h"
#import "ContactDBAccessor.h"
#import "UidDBAccessor.h"
#import "StoreObserver.h"
#import <StoreKit/StoreKit.h>
@implementation ReMailAppDelegate
@synthesize window;
@synthesize pushSetupScreen;
-(void)dealloc {
[window release];
[super dealloc];
}
-(void)deactivateAllPurchases {
// This is debug code, it should never be called in production
[AppSettings setFeatureUnpurchased:@"RM_NOADS"];
[AppSettings setFeatureUnpurchased:@"RM_IMAP"];
[AppSettings setFeatureUnpurchased:@"RM_RACKSPACE"];
}
-(void)activateAllPurchasedFeatures {
[AppSettings setFeaturePurchased:@"RM_NOADS"];
[AppSettings setFeaturePurchased:@"RM_IMAP"];
[AppSettings setFeaturePurchased:@"RM_RACKSPACE"];
}
-(void)pingHomeThread {
// ping home to www.remail.com - this is for user # tracking only and does not send any
// personally identifiable or usage information
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString* model = [[AppSettings model] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
model = [model stringByReplacingOccurrencesOfString:@"?" withString:@"%3F"];
model = [model stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
int edition = (int)[AppSettings reMailEdition];
NSString *encodedPostString = [NSString stringWithFormat:@"umd=%@&m=%@&v=%@&sv=%@&e=%i", md5([AppSettings udid]), model, [AppSettings version], [AppSettings systemVersion], edition];
NSLog(@"pingRemail: %@", encodedPostString);
NSData *postData = [encodedPostString dataUsingEncoding:NSUTF8StringEncoding];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.remail.com/ping"]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:postData];
// Execute HTTP call
NSHTTPURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if((!error) && ([(NSHTTPURLResponse *)response statusCode] == 200) && ([responseData length] > 0)) {
[AppSettings setPinged];
} else {
NSLog(@"Invalid ping response %i", [(NSHTTPURLResponse *)response statusCode]);
}
[request release];
[pool release];
}
-(void)pingHome {
NSThread *driverThread = [[NSThread alloc] initWithTarget:self selector:@selector(pingHomeThread) object:nil];
[driverThread start];
[driverThread release];
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Failed push registration with error: %@", error);
// I feel like this is kind of a hack
if(self.pushSetupScreen != nil && [self.pushSetupScreen respondsToSelector:@selector(didFailToRegisterForRemoteNotificationsWithError:)]) {
[self.pushSetupScreen performSelectorOnMainThread:@selector(didFailToRegisterForRemoteNotificationsWithError:) withObject:error waitUntilDone:NO];
}
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken {
// Get a hex string from the device token with no spaces or < >
NSString* deviceToken = [[[[_deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"Device Token: %@", deviceToken);
if(self.pushSetupScreen != nil && [self.pushSetupScreen respondsToSelector:@selector(didRegisterForRemoteNotificationsWithDeviceToken:)]) {
[self.pushSetupScreen performSelectorOnMainThread:@selector(didRegisterForRemoteNotificationsWithDeviceToken:) withObject:deviceToken waitUntilDone:NO];
}
}
-(void)resetApp {
// reset - delete all data and settings
[AppSettings setReset:NO];
for(int i = 0; i < [AppSettings numAccounts]; i++) {
[AppSettings setUsername:@"" accountNum:i];
[AppSettings setPassword:@"" accountNum:i];
[AppSettings setServer:@"" accountNum:i];
[AppSettings setAccountDeleted:YES accountNum:0];
}
[AppSettings setLastpos:@"home"];
[AppSettings setDataInitVersion];
[AppSettings setFirstSync:YES];
[AppSettings setGlobalDBVersion:0];
[AppSettings setNumAccounts:0];
[GlobalDBFunctions deleteAll];
}
-(void)setImapErrorLogPath {
NSString* mailimapErrorLogPath = [StringUtil filePathInDocumentsDirectoryForFileName:@"mailimap_error.log"];
const char* a = [mailimapErrorLogPath cStringUsingEncoding:NSASCIIStringEncoding];
setenv("REMAIL_MAILIMAP_ERROR_LOG_PATH", a, 1);
// delete file that might have been left around
if ([[NSFileManager defaultManager] fileExistsAtPath:mailimapErrorLogPath]) {
[[NSFileManager defaultManager] removeItemAtPath:mailimapErrorLogPath error:NULL];
}
}
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)options {
[NSThread setThreadPriority:1.0];
// set path for log output to send home
[self setImapErrorLogPath];
// handle reset and clearing attachments
// (the user can reset all data in iPhone > Settings)
if([AppSettings reset]) {
[self resetApp];
}
// we're not selling reMail any more, so we can just activate all purchases
[self activateAllPurchasedFeatures];
BOOL firstSync = [AppSettings firstSync];
if(firstSync) {
[AppSettings setDatastoreVersion:1];
//Need to set up first account
AccountTypeSelectViewController* accountTypeVC;
accountTypeVC = [[AccountTypeSelectViewController alloc] initWithNibName:@"AccountTypeSelect" bundle:nil];
accountTypeVC.firstSetup = YES;
accountTypeVC.accountNum = 0;
accountTypeVC.newAccount = YES;
UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:accountTypeVC];
[self.window addSubview:navController.view];
[accountTypeVC release];
} else {
// already set up - let's go to the home screen
HomeViewController *homeController = [[HomeViewController alloc] initWithNibName:@"HomeView" bundle:nil];
UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:homeController];
navController.navigationBarHidden = NO;
[self.window addSubview:navController.view];
if(options != nil) {
[homeController loadIt];
[homeController toolbarRefreshClicked:nil];
}
[homeController release];
}
[window makeKeyAndVisible];
//removed after I cut out store
//[[SKPaymentQueue defaultQueue] addTransactionObserver:[StoreObserver getSingleton]];
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application {
EmailProcessor *em = [EmailProcessor getSingleton];
em.shuttingDown = YES;
SearchRunner *sem = [SearchRunner getSingleton];
[sem cancel];
// write unwritten changes to user defaults to disk
[NSUserDefaults resetStandardUserDefaults];
[EmailProcessor clearPreparedStmts];
[EmailProcessor finalClearPreparedStmts];
[SearchRunner clearPreparedStmts];
// Close the databases
[[AddEmailDBAccessor sharedManager] close];
[[SearchEmailDBAccessor sharedManager] close];
[[ContactDBAccessor sharedManager] close];
[[UidDBAccessor sharedManager] close];
}
- (void)applicationWillResignActive:(UIApplication *)application {
//TODO(gabor): Cancel any ongoing sync, remember that a sync was ongoing
NSLog(@"applicationWillResignActive");
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// If a sync was ongoing, restart it
NSLog(@"applicationDidBecomeActive");
}
@end
|
zzj9008-aaa
|
Classes/ReMailAppDelegate.m
|
Objective-C
|
asf20
| 8,742
|
/*
Copyright (c) 2007, Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
@mainpage A strict JSON parser and generator for Objective-C
JSON (JavaScript Object Notation) is a lightweight data-interchange
format. This framework provides two apis for parsing and generating
JSON. One standard object-based and a higher level api consisting of
categories added to existing Objective-C classes.
Learn more on the http://code.google.com/p/json-framework project site.
*/
#import "SBJSON.h"
#import "NSObject+SBJSON.h"
#import "NSString+SBJSON.h"
|
zzj9008-aaa
|
Classes/JSON.h
|
Objective-C
|
asf20
| 1,963
|
//
// UidDBAccessor.m
// ----------------------------------------------------------------------
// Part of the SQLite Persistent Objects for Cocoa and Cocoa Touch
//
// Original Version: (c) 2008 Jeff LaMarche (jeff_Lamarche@mac.com)
// ----------------------------------------------------------------------
// This code may be used without restriction in any software, commercial,
// free, or otherwise. There are no attribution requirements, and no
// requirement that you distribute your changes, although bugfixes and
// enhancements are welcome.
//
// If you do choose to re-distribute the source code, you must retain the
// copyright notice and this license information. I also request that you
// place comments in to identify your changes.
//
// For information on how to use these classes, take a look at the
// included Readme.txt file
// ----------------------------------------------------------------------
#import "UidDBAccessor.h"
#import "StringUtil.h"
#define UID_DB_NAME @"uid.tdb"
static UidDBAccessor *sharedSQLiteManager = nil;
#pragma mark Private Method Declarations
@interface UidDBAccessor (private)
- (void)executeUpdateSQL:(NSString *) updateSQL;
@end
@implementation UidDBAccessor
#pragma mark -
#pragma mark Singleton Methods
+ (id)sharedManager
{
@synchronized(self)
{
if (sharedSQLiteManager == nil) {
sharedSQLiteManager = [[[self alloc] init] retain];;
}
}
return sharedSQLiteManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedSQLiteManager == nil) {
sharedSQLiteManager = [[super allocWithZone:zone] retain];
}
}
return sharedSQLiteManager;
return nil;
}
//Einar added for sanity.
+ (BOOL)beginTransaction
{
const char *sql1 = "BEGIN TRANSACTION"; //Should be exclusive?
sqlite3_stmt *begin_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql1, -1, &begin_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(begin_statement);
return NO;
}
if (sqlite3_step(begin_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in beginTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(begin_statement);
return NO;
}
sqlite3_finalize(begin_statement);
return YES;
}
+ (BOOL)endTransaction
{
const char *sql2 = "COMMIT TRANSACTION";
sqlite3_stmt *commit_statement;
if (sqlite3_prepare_v2([[self sharedManager] database], sql2, -1, &commit_statement, NULL) != SQLITE_OK)
{
sqlite3_finalize(commit_statement);
return NO;
}
if (sqlite3_step(commit_statement) != SQLITE_DONE)
{
NSLog(@"Failed step in endTransaction with error %s", sqlite3_errmsg([[self sharedManager] database]));
sqlite3_finalize(commit_statement);
return NO;
}
sqlite3_finalize(commit_statement);
return YES;
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
// never release
}
- (id)autorelease
{
return self;
}
#pragma mark -
#pragma mark Public Instance Methods
-(sqlite3 *)database
{
static BOOL first = YES;
if (first || database == NULL)
{
first = NO;
if (!sqlite3_open([[self databaseFilepath] UTF8String], &database) == SQLITE_OK)
{
NSAssert1(0, @"Attempted to open database at path %s, but failed",[[self databaseFilepath] UTF8String]);
// Even though the open failed, call close to properly clean up resources.
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
sqlite3_close(database);
}
else
{
// Modify cache size so we don't overload memory. 50 * 1.5kb
[self executeUpdateSQL:@"PRAGMA CACHE_SIZE=500"];
// Default to UTF-8 encoding
[self executeUpdateSQL:@"PRAGMA encoding = \"UTF-8\""];
// Turn on full auto-vacuuming to keep the size of the database down
// This setting can be changed per database using the setAutoVacuum instance method
[self executeUpdateSQL:@"PRAGMA auto_vacuum=1"];
}
}
return database;
}
-(void)close {
// close DB
if(database != NULL) {
sqlite3_close(database);
database = NULL;
}
}
- (void)setAutoVacuum:(SQLITE3AutoVacuum)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA auto_vacuum=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)setCacheSize:(NSUInteger)pages
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", pages];
[self executeUpdateSQL:updateSQL];
}
- (void)setLockingMode:(SQLITE3LockingMode)mode
{
NSString *updateSQL = [NSString stringWithFormat:@"PRAGMA cache_size=%d", mode];
[self executeUpdateSQL:updateSQL];
}
- (void)deleteDatabase
{
NSString* path = [self databaseFilepath];
NSFileManager* fm = [NSFileManager defaultManager];
[fm removeItemAtPath:path error:nil];
database = NULL;
}
- (void)vacuum
{
[self executeUpdateSQL:@"VACUUM"];
}
#pragma mark -
- (void)dealloc{
[super dealloc];
}
#pragma mark -
#pragma mark Private Methods
- (void)executeUpdateSQL:(NSString *) updateSQL
{
char *errorMsg;
if (sqlite3_exec([self database],[updateSQL UTF8String] , NULL, NULL, &errorMsg) != SQLITE_OK) {
NSString *errorMessage = [NSString stringWithFormat:@"Failed to execute SQL '%@' with message '%s'.", updateSQL, errorMsg];
NSAssert(0, errorMessage);
sqlite3_free(errorMsg);
}
}
- (NSString *)databaseFilepath {
return [StringUtil filePathInDocumentsDirectoryForFileName:UID_DB_NAME];
}
@end
|
zzj9008-aaa
|
Classes/UidDBAccessor.m
|
Objective-C
|
asf20
| 5,486
|